HttpClient简介

http://www.diybl.com/course/3_program/java/javashl/20100106/186854.html  
HttpClient简介 
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。 
Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给 httpclient替你完成。 
  
首先,我们必须安装好 HttpClient。 
HttpClient 可以在http://jakarta.apache.org/commons/httpclient/downloads.html下载. 
  
HttpClient 用到了 Apache Jakarta common 下的子项目 logging,你可以从这个地址http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi下载到 common logging,从下载后的压缩包中取出 commons-logging.jar 加到 CLASSPATH 中. 
  
HttpClient 用到了 Apache Jakarta common 下的子项目 codec,你可以从这个地址http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi 下载到最新的 common codec,从下载后的压缩包中取出 commons-codec-1.x.jar 加到 CLASSPATH 中 
  
1. 读取网页(HTTP/HTTPS)内容 
下面是我们给出的一个简单的例子用来访问某个页面 

Java代码   收藏代码
  1. package http.demo;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.commons.httpclient.*;   
  6.   
  7. import org.apache.commons.httpclient.methods.*;   
  8.   
  9. /**  
  10.  
  11. * 最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面  
  12.  
  13. * @author Liudong  
  14.  
  15. */   
  16.   
  17. public class SimpleClient {   
  18.   
  19.         public static void main(String[] args) throws IOException   
  20.   
  21.         {   
  22.   
  23.                 HttpClient client = new HttpClient();          
  24.   
  25.                 //设置代理服务器地址和端口           
  26.   
  27.                 //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);   
  28.   
  29.                 //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https   
  30.   
  31.                 HttpMethod method = new GetMethod("http://java.sun.com");   
  32.   
  33.                 //使用POST方法   
  34.   
  35.                 //HttpMethod method = new PostMethod("http://java.sun.com");   
  36.   
  37.                 client.executeMethod(method);   
  38.   
  39.                 //打印服务器返回的状态   
  40.   
  41.                 System.out.println(method.getStatusLine());   
  42.   
  43.                 //打印返回的信息   
  44.   
  45.                 System.out.println(method.getResponseBodyAsString());   
  46.   
  47.                 //释放连接   
  48.   
  49.                 method.releaseConnection();   
  50.   
  51.         }   
  52. }   

在这个例子中首先创建一个HTTP客户端(HttpClient)的实例,然后选择提交的方法是GET或者 POST,最后在HttpClient实例上执行提交的方法,最后从所选择的提交方法中读取服务器反馈回来的结果。这就是使用HttpClient的基本流程。其实用一行代码也就可以搞定整个请求的过程,非常的简单! 
  
2. 以GET或者POST方式向网页提交参数 

其实前面一个最简单的示例中我们已经介绍了如何使用GET或者POST方式来请求一个页面,本小节与之不同的是多了提交时设定页面所需的参数,我们知道如果是GET的请求方式,那么所有参数都直接放到页面的URL后面用问号与页面地址隔开,每个参数用&隔开,例如:http://java.sun.com?name=liudong&mobile=123456,但是当使用POST方法时就会稍微有一点点麻烦。本小节的例子演示向如何查询手机号码所在的城市,代码如下: 

NameValuePair: 
简单名称值对节点类NameValuePair. 摘要: 本类位于System. ... NameValuePair。主要用途是在DBConnectionString类中,解析ConnectionString时存储并串联Name/Value对。 

Java代码   收藏代码
  1. package http.demo;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.commons.httpclient.*;   
  6.   
  7. import org.apache.commons.httpclient.methods.*;   
  8.   
  9. /**  
  10.  
  11. * 提交参数演示  
  12.  
  13. * 该程序连接到一个用于查询手机号码所属地的页面  
  14.  
  15. * 以便查询号码段1330227所在的省份以及城市  
  16.  
  17. * @author Liudong  
  18.  
  19. */   
  20.   
  21. public class SimpleHttpClient {   
  22.   
  23.         public static void main(String[] args) throws IOException   
  24.   
  25.         {   
  26.   
  27.                 HttpClient client = new HttpClient();   
  28.   
  29.                 client.getHostConfiguration().setHost("www.imobile.com.cn"80"http");   
  30.   
  31.                 HttpMethod method = getPostMethod();//使用POST方式提交数据   
  32.   
  33.                 client.executeMethod(method);   
  34.   
  35.              //打印服务器返回的状态   
  36.   
  37.                 System.out.println(method.getStatusLine());   
  38.   
  39.                 //打印结果页面   
  40.   
  41.                 String response =   
  42.   
  43.                      new String(method.getResponseBodyAsString().getBytes("8859_1"));   
  44.   
  45.              //打印返回的信息   
  46.   
  47.                 System.out.println(response);   
  48.   
  49.                 method.releaseConnection();   
  50.   
  51.         }   
  52.   
  53.         /**  
  54.  
  55.          * 使用GET方式提交数据 
  56. ;  * @return  
  57.  
  58.          */   
  59.   
  60.         private static HttpMethod getGetMethod(){   
  61.   
  62.                 return new GetMethod("/simcard.php?simcard=1330227");   
  63.   
  64.         }   
  65.   
  66.         /**  
  67.  
  68.          * 使用POST方式提交数据  
  69.  
  70.          * @return  
  71.  
  72.          */   
  73.   
  74.         private static HttpMethod getPostMethod(){   
  75.   
  76.                 PostMethod post = new PostMethod("/simcard.php");   
  77.   
  78.                 NameValuePair simcard = new NameValuePair("simcard","1330227");   
  79.   
  80.                 post.setRequestBody(new NameValuePair[] { simcard});   
  81.   
  82.                 return post;   
  83.   
  84.         }   
  85.   
  86. }   

在上面的例子中页面http://www.imobile.com.cn/simcard.php需要一个参数是simcard,这个参数值为手机号码段,即手机号码的前七位,服务器会返回提交的手机号码对应的省份、城市以及其他详细信息。GET的提交方法只需要在URL后加入参数信息,而POST则需要通过NameValuePair类来设置参数名称和它所对应的值. 
  
3. 处理页面重定向 

在JSP/Servlet编程中response.sendRedirect方法就是使用HTTP协议中的重定向机制。它与JSP中的<jsp:forward …>的区别在于后者是在服务器中实现页面的跳转,也就是说应用容器加载了所要跳转的页面的内容并返回给客户端;而前者是返回一个状态码,这些状态码的可能值见下表,然后客户端读取需要跳转到的页面的URL并重新加载新的页面。就是这样一个过程,所以我们编程的时候就要通过 HttpMethod.getStatusCode()方法判断返回值是否为下表中的某个值来判断是否需要跳转。如果已经确认需要进行页面跳转了,那么可以通过读取HTTP头中的location属性来获取新的地址。 

状态码 
对应HttpServletResponse的常量 
详细描述 

301 
SC_MOVED_PERMANENTLY 
页面已经永久移到另外一个新地址 

302 
SC_MOVED_TEMPORARILY 
页面暂时移动到另外一个新的地址 

303 
SC_SEE_OTHER 
客户端请求的地址必须通过另外的URL来访问 

307 
SC_TEMPORARY_REDIRECT 
同SC_MOVED_TEMPORARILY 


下面的代码片段演示如何处理页面的重定向 

Java代码   收藏代码
  1. client.executeMethod(post);   
  2.   
  3.                 System.out.println(post.getStatusLine().toString());   
  4.   
  5.                 post.releaseConnection();   
  6.   
  7.                   
  8.   
  9.                 //检查是否重定向   
  10.   
  11.                 int statuscode = post.getStatusCode();   
  12.   
  13.                 if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||   
  14.   
  15.                         (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||   
  16.   
  17.                         (statuscode == HttpStatus.SC_SEE_OTHER) ||   
  18.   
  19. (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {   
  20.   
  21. //读取新的URL地址   
  22.   
  23.                         Header header = post.getResponseHeader("location");   
  24.   
  25.                         if (header != null) {   
  26.   
  27.                                 String newuri = header.getValue();   
  28.   
  29.                                 if ((newuri == null) || (newuri.equals("")))   
  30.   
  31.                                         newuri = "/";   
  32.   
  33.                                 GetMethod redirect = new GetMethod(newuri);   
  34.   
  35.                                 client.executeMethod(redirect);   
  36.   
  37.                                 System.out.println("Redirect:"+ redirect.getStatusLine().toString());   
  38.   
  39.                                 redirect.releaseConnection();   
  40.   
  41.                         } else   
  42.   
  43.                                 System.out.println("Invalid redirect");   
  44.   
  45.                 }   

我们可以自行编写两个JSP页面,其中一个页面用response.sendRedirect方法重定向到另外一个页面用来测试上面的例子。 
  
4. 模拟输入用户名和口令进行登录 

Java代码   收藏代码
  1. /*  
  2.  
  3. * Created on 2003-12-7 by Liudong  
  4.  
  5. */   
  6.   
  7. package http.demo;   
  8.   
  9. import org.apache.commons.httpclient.*;   
  10.   
  11. import org.apache.commons.httpclient.cookie.*;   
  12.   
  13. import org.apache.commons.httpclient.methods.*;   
  14.   
  15. /**  
  16.  
  17. * 用来演示登录表单的示例  
  18.  
  19. * @author Liudong  
  20.  
  21. */   
  22.   
  23. public class   
  24.   
  25. FormLoginDemo {   
  26.   
  27.         static final String LOGON_SITE = "localhost";   
  28.   
  29.         static final int        LOGON_PORT = 8080;   
  30.   
  31.           
  32.   
  33.         public static void main(String[] args) throws Exception{   
  34.   
  35.                 HttpClient client = new HttpClient();   
  36.   
  37.                 client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);   
  38.   
  39.                
  40.   
  41.              //模拟登录页面login.jsp->main.jsp   
  42.   
  43.                 PostMethod post = new PostMethod("/main.jsp");   
  44.   
  45.                 NameValuePair name = new NameValuePair("name""ld");           
  46.   
  47.                 NameValuePair pass = new NameValuePair("password""ld");           
  48.   
  49.                 post.setRequestBody(new NameValuePair[]{name,pass});   
  50.   
  51.              int status = client.executeMethod(post);   
  52.   
  53.                 System.out.println(post.getResponseBodyAsString());   
  54.   
  55.                 post.releaseConnection();   
  56.   
  57.                
  58.   
  59.              //查看cookie信息   
  60.   
  61.                 CookieSpec cookiespec = CookiePolicy.getDefaultSpec();   
  62.   
  63.                 Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/"false, client.getState().getCookies());   
  64.   
  65.              if (cookies.length == 0) {   
  66.   
  67.                      System.out.println("None");          
  68.   
  69.              } else {   
  70.   
  71.                      for (int i = 0; i < cookies.length; i++) {   
  72.   
  73.                              System.out.println(cookies[i].toString());          
  74.   
  75.                      }   
  76.   
  77.              }   
  78.   
  79.              //访问所需的页面main2.jsp   
  80.   
  81.                 GetMethod get = new GetMethod("/main2.jsp");   
  82.   
  83.                 client.executeMethod(get);   
  84.   
  85.                 System.out.println(get.getResponseBodyAsString());   
  86.   
  87.                 get.releaseConnection();   
  88.   
  89.         }   
  90.   
  91. }   
5. 提交XML格式参数 
提交XML格式的参数很简单,仅仅是一个提交时候的ContentType问题,下面的例子演示从文件文件中读取XML信息并提交给服务器的过程,该过程可以用来测试Web服务。 

Java代码   收藏代码
  1. import java.io.File;   
  2.   
  3. import java.io.FileInputStream;   
  4.   
  5. import org.apache.commons.httpclient.HttpClient;   
  6.   
  7. import org.apache.commons.httpclient.methods.EntityEnclosingMethod;   
  8.   
  9. import org.apache.commons.httpclient.methods.PostMethod;   
  10.   
  11. /**  
  12.  
  13. * 用来演示提交XML格式数据的例子  
  14.  
  15. */   
  16.   
  17. public class PostXMLClient {   
  18.   
  19.         public static void main(String[] args) throws Exception {   
  20.   
  21.                 File input = new File(“test.xml”);   
  22.   
  23.                 PostMethod post = new PostMethod(“http://localhost:8080/httpclient/xml.jsp”);   
  24.   
  25.                 // 设置请求的内容直接从文件中读取   
  26.   
  27.                 post.setRequestBody(new FileInputStream(input));   
  28.   
  29.                   
  30.   
  31.                 if (input.length() < Integer.MAX_VALUE)   
  32.   
  33.                         post.setRequestContentLength(input.length());   
  34.   
  35.                 else  
  36. post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);   
  37.   
  38.                   
  39.   
  40.                 // 指定请求内容的类型   
  41.   
  42.                 post.setRequestHeader("Content-type""text/xml; charset=GBK");   
  43.   
  44.                   
  45.   
  46.                 HttpClient httpclient = new HttpClient();   
  47.   
  48.                 int result = httpclient.executeMethod(post);   
  49.   
  50.                 System.out.println("Response status code: " + result);   
  51.   
  52.                 System.out.println("Response body: ");   
  53.   
  54.                 System.out.println(post.getResponseBodyAsString());   
  55.   
  56.                 post.releaseConnection();   
  57.   
  58.         }   
  59.   
  60. }  

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服务器中下载的,它简单演示如何访问一个认证保护的页面: 


Java代码   收藏代码
  1. import org.apache.commons.httpclient.HttpClient;   
  2.   
  3. import org.apache.commons.httpclient.UsernamePasswordCredentials;   
  4.   
  5. import org.apache.commons.httpclient.methods.GetMethod;   
  6.   
  7. public class BasicAuthenticationExample {   
  8.   
  9.         public BasicAuthenticationExample() {   
  10.   
  11.         }   
  12.   
  13.         public static void main(String[] args) throws Exception {   
  14.   
  15.                 HttpClient client = new HttpClient();   
  16.   
  17.                 client.getState().setCredentials(   
  18.   
  19.                         "www.verisign.com",   
  20.   
  21.                         "realm",   
  22.   
  23.                         new UsernamePasswordCredentials("username""password")   
  24.   
  25.                 );   
  26.   
  27.                 GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");   
  28.   
  29.                 get.setDoAuthentication( true );   
  30.   
  31.                 int status = client.executeMethod( get );   
  32.   
  33.                 System.out.println(status+""+ get.getResponseBodyAsString());   
  34.   
  35.                 get.releaseConnection();   
  36.   
  37.         }   
  38.   
  39. }   

8. 多线程模式下使用httpclient 


多线程同时访问httpclient,例如同时从一个站点上下载多个文件。对于同一个HttpConnection 同一个时间只能有一个线程访问,为了保证多线程工作环境下不产生冲突,httpclient使用了一个多线程连接管理器的类: MultiThreadedHttpConnectionManager,要使用这个类很简单,只需要在构造HttpClient实例的时候传入即可,代码如下: 

MultiThreadedHttpConnectionManager connectionManager = 

     new MultiThreadedHttpConnectionManager(); 

HttpClient client = new HttpClient(connectionManager); 

以后尽管访问client实例即可。 
  

httpclient的多线程处理 

  使用多线程的主要目的,是为了实现并行的下载。在httpclient运行的过程中,每个http协议的方法,使用一个HttpConnection实例。由于连接是一种有限的资源,每个连接在某一时刻只能供一个线程和方法使用,所以需要确保在需要时正确地分配连接。HttpClient采用了一种类似jdbc连接池的方法来管理连接,这个管理工作由 MultiThreadedHttpConnectionManager完成。 

MultiThreadedHttpConnectionManager connectionManager = 

new MultiThreadedHttpConnectionManager(); 

HttpClient client = new HttpClient(connectionManager); 

此是,client可以在多个线程中被用来执行多个方法。每次调用 HttpClient.executeMethod() 方法,都会去链接管理器申请一个连接实例,申请成功这个链接实例被签出(checkout),随之在链接使用完后必须归还管理器。管理器支持两个设置: maxConnectionsPerHost 每个主机的最大并行链接数,默认为2 

maxTotalConnections 客户端总并行链接最大数,默认为20 

  管理器重新利用链接时,采取早归还者先重用的方式(least recently used approach)。 

  由于是使用HttpClient的程序而不是HttpClient本身来读取应答包的主体,所以HttpClient无法决定什么时间连接不再使用了,这也就要求在读完应答包的主体后必须手工显式地调用releaseConnection()来释放申请的链接。 

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); 

HttpClient client = new HttpClient(connectionManager); 

... 

// 在某个线程中。 

GetMethod get = new GetMethod("http://jakarta.apache.org/"); 

try { 

client.executeMethod(get); 

// print response to stdout 

System.out.println(get.getRsponseBodyAsStream()); 
} finally { 

// be sure the connection is released back to the connection 

// manager 

get.releaseConnection(); 




对每一个HttpClient.executeMethod须有一个method.releaseConnection()与之匹配 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值