client.executeMethod(post);
System.out.println(post.getStatusLine().toString());
post.releaseConnection();
//
检查是否重定向
int
statuscode
=
post.getStatusCode();
if
((statuscode
==
HttpStatus.SC_MOVED_TEMPORARILY)
||
(statuscode
==
HttpStatus.SC_MOVED_PERMANENTLY)
||
(statuscode
==
HttpStatus.SC_SEE_OTHER)
||
(statuscode
==
HttpStatus.SC_TEMPORARY_REDIRECT))
{//读取新的URL地址
Header header = post.getResponseHeader("location");
if (header != null) {
String newuri = header.getValue();
if ((newuri == null) || (newuri.equals("")))
newuri = "/";
GetMethod redirect = new GetMethod(newuri);
client.executeMethod(redirect);
System.out.println("Redirect:"+ redirect.getStatusLine().toString());
redirect.releaseConnection();
} else {
System.out.println("Invalid redirect");
} 咱们能够自行编写两个JSP页面,其中一个页面用response.sendRedirect方法重定向到另一个页面用来测试上面的例子。
4. 模拟输入用户名和口令进行登陆
本 小节应该说是HTTP客户端编程中最常遇见的问题,不少网站的内容都只是对注册用户可见的,这种状况下就必需要求使用正确的用户名和口令登陆成功后,方可 浏览到想要的页面。由于HTTP协议是无状态的,也就是链接的有效期只限于当前请求,请求内容结束后链接就关闭了。在这种状况下为了保存用户的登陆信息必 须使用到Cookie机制。以JSP/Servlet为例,当浏览器请求一个JSP或者是Servlet的页面时,应用服务器会返回一个参数,名为 jsessionid(因不一样应用服务器而异),值是一个较长的惟一字符串的Cookie,这个字符串值也就是当前访问该站点的会话标识。浏览器在每访问 该站点的其余页面时候都要带上jsessionid这样的Cookie信息,应用服务器根据读取这个会话标识来获取对应的会话信息。
对于 须要用户登陆的网站,通常在用户登陆成功后会将用户资料保存在服务器的会话中,这样当访问到其余的页面时候,应用服务器根据浏览器送上的Cookie中读 取当前请求对应的会话标识以得到对应的会话信息,而后就能够判断用户资料是否存在于会话信息中,若是存在则容许访问页面,不然跳转到登陆页面中要求用户输 入账号和口令进行登陆。这就是通常使用JSP开发网站在处理用户登陆的比较通用的方法。
这样一来,对于HTTP的客户端来说,若是要访问 一个受保护的页面时就必须模拟浏览器所作的工做,首先就是请求登陆页面,而后读取Cookie值;再次请求登陆页面并加入登陆页所需的每一个参数;最后就是 请求最终所需的页面。固然在除第一次请求外其余的请求都须要附带上Cookie信息以便服务器能判断当前请求是否已经经过验证。说了这么多,但是若是你使 用httpclient的话,你甚至连一行代码都无需增长,你只须要先传递登陆信息执行登陆过程,而后直接访问想要的页面,跟访问一个普通的页面没有任何 区别,由于类HttpClient已经帮你作了全部该作的事情了,太棒了!下面的例子实现了这样一个访问的过程。
/*
* Created on 2003-12-7 by Liudong
*/
package
http.demo;
import
org.apache.commons.httpclient.
*
;
import
org.apache.commons.httpclient.cookie.
*
;
import
org.apache.commons.httpclient.methods.
*
;
/**
* 用来演示登陆表单的示例
* @author Liudong
*/
public
class
FormLoginDemo
{
static final String LOGON_SITE = "localhost";
static final int LOGON_PORT = 8080;
public static void main(String[] args) throws Exception{
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
//模拟登陆页面login.jsp->main.jsp
PostMethod post = new PostMethod("/main.jsp");
NameValuePair name = new NameValuePair("name", "ld");
NameValuePair pass = new NameValuePair("password", "ld");
post.setRequestBody(new NameValuePair[]{name,pass});
int status = client.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
//查看cookie信息
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
if (cookies.length == 0) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.length; i++) {
System.out.println(cookies[i].toString());
}
}
//访问所需的页面main2.jsp
GetMethod get = new GetMethod("/main2.jsp");
client.executeMethod(get);
System.out.println(get.getResponseBodyAsString());
get.releaseConnection();
}
}
5. 提交XML格式参数
提交XML格式的参数很简单,仅仅是一个提交时候的ContentType问题,下面的例子演示从文件文件中读取XML信息并提交给服务器的过程,该过程能够用来测试Web服务。
import
java.io.File;
import
java.io.FileInputStream;
import
org.apache.commons.httpclient.HttpClient;
import
org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import
org.apache.commons.httpclient.methods.PostMethod;
/**
* 用来演示提交XML格式数据的例子
*/
public
class
PostXMLClient
{
public static void main(String[] args) throws Exception {
File input = new File(“test.xml”);
PostMethod post = new PostMethod(“http://localhost:8080/httpclient/xml.jsp”);
// 设置请求的内容直接从文件中读取
post.setRequestBody(new FileInputStream(input));
if (input.length() < Integer.MAX_VALUE)
post.setRequestContentLength(input.length());
else
post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
// 指定请求内容的类型
post.setRequestHeader("Content-type", "text/xml; charset=GBK");
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
}
}
6. 经过HTTP上传文件
httpclient使用了单独的一个HttpMethod子类来处理文件的上传,这个类就是MultipartPostMethod,该类已经封装了文件上传的细节,咱们要作的仅仅是告诉它咱们要上传文件的全路径便可,下面的代码片断演示如何使用这个类。
MultipartPostMethod filePost
=
new
MultipartPostMethod(targetURL);
filePost.addParameter(
"
fileName
"
, targetFilePath);
HttpClient client
=
new
HttpClient();
//
因为要上传的文件可能比较大,所以在此设置最大的链接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(
5000
);
int
status
=
client.executeMethod(filePost);
上面代码中,targetFilePath即为要上传的文件所在的路径。
7. 访问启用认证的页面
我 们常常会碰到这样的页面,当访问它的时候会弹出一个浏览器的对话框要求输入用户名和密码后方可,这种用户认证的方式不一样于咱们在前面介绍的基于表单的用户 身份验证。这是HTTP的认证策略,httpclient支持三种认证方式包括:基本、摘要以及NTLM认证。其中基本认证最简单、通用但也最不安全;摘 要认证是在HTTP 1.1中加入的认证方式,而NTLM则是微软公司定义的而不是通用的规范,最新版本的NTLM是比摘要认证还要安全的一种方式。
下面例子是从httpclient的CVS服务器中下载的,它简单演示如何访问一个认证保护的页面:
import
org.apache.commons.httpclient.HttpClient;
import
org.apache.commons.httpclient.UsernamePasswordCredentials;
import
org.apache.commons.httpclient.methods.GetMethod;
public
class
BasicAuthenticationExample
{
public BasicAuthenticationExample() {
}
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
client.getState().setCredentials(
"www.verisign.com",
"realm",
new UsernamePasswordCredentials("username", "password")
);
GetMethod get = new GetMethod("https://www.verisign.com/products/index.html";);
get.setDoAuthentication( true );
int status = client.executeMethod( get );
System.out.println(status+""+ get.getResponseBodyAsString());
get.releaseConnection();
}
}
8. 多线程模式下使用httpclient
多 线程同时访问httpclient,例如同时从一个站点上下载多个文件。对于同一个HttpConnection同一个时间只能有一个线程访问,为了保证 多线程工做环境下不产生冲突,httpclient使用了一个多线程链接管理器的类: MultiThreadedHttpConnectionManager,要使用这个类很简单,只须要在构造HttpClient实例的时候传入便可,代 码以下:
MultiThreadedHttpConnectionManager connectionManager
=
new
MultiThreadedHttpConnectionManager();
HttpClient client
=
new
HttpClient(connectionManager);