`
michaeltangbin
  • 浏览: 268111 次
  • 性别: Icon_minigender_1
  • 来自: 黑龙江省
社区版块
存档分类
最新评论

HttpClient的使用

    博客分类:
  • java
阅读更多

HttpClient 简介
HTTP 协议可能是现在 Internet 上使用得最多,最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用乘车来说, JDK 库本身提供的功能还不够丰富和灵活。 HttpClient Apache Jakarta Common 下的子项目,用来提供高校的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上有很著名的另外两个开源项目 Cactus HTMLUnit 都使用了 HttpClient ,更多使用 HttpClient 的应用可以参见 http://wiki.apache.org/jakarta-httpclient/HttpClientPowered HttpClient 项目非常活跃,使用的人还是很多。
HttpClient 功能介绍
以下列出的是 HttpClient 提供的主要的功能,要更多知道相信的功能请参见 HttpClient 主页。
 
1 、实现了所有的 HTTP 的方法 (GET,POST,PUT,HEAD )
2 、支持自动转向
3 、支持 HTTPS 协议
4 、支持代理服务器等

实现步骤:

1
、首先是安装 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
2 HttpClient 基本功能的使用
GET 方法:
使用 HttpClient 需要以下 6 个步骤:
1
、创建 HttpClient 实例
2 、创建某种连接方法的实例,在这里是 GetMEthod 。在 GetMethd 的构造函数中传入待连接的地址
3 、调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4 、读 response
5 、释放连接,无论执行方法是否成功,都必须释放连接。
6 、对得到后的内容进行处理

实例:
更具以上步骤,我们来写一个 GET 方法来取得某网页内容的代码。

大部分情况下 HttpClient 默认的构造函数已经足够使用。
HttpClient httpClient = new HttpClient();
1
创建 GET 方法的实例。在 Get 方法的构造函数中传入带连接的地址即可。用 GetMethod 将会自动处理转发过程,如果想要把自动处理转发过程去掉的话,可以调用方法 setFollowRedirects(false).
GetMethod getMethod = new GetMethod("http://www.ibm.com/");
2
调用实例 httpclient executeMethod 方法来执行 getMethod 。由于是执行在网络上的程序,在运行 executeMethod 方法的时候,需要处理两个异常,分别是 HttpException IOException 。引起第一种异常的原因主要可能是在构造 getMethod 的时候传入的协议不对,比如不小心将 http 写成 htp ,或者服务器端返回的内容不正常等,并且该异常发生是不可恢复的 ; 第二种异常一般是由于我哪敢来原因引起的异常,对于这种异常 (IOException) HttpClient 会根据你指定的恢复策略自动试着重新执行 executeMethod 方法。 HttpClient 的恢复策略可以自定义(通过实现接口 HttpMethodRetryHandle 来实现)。通过 HttpClient 的方法 setParameter 设置你实现的恢复策略,这里使用的是系统提供的默认的恢复策略,该策略在碰到第二类异常的时候将自动重试 3 此。 executeMethod 返回值是一个整数,表示了执行该方法后服务器返回的状态码,该状态码能表示出该方法执行是否成功、需要认证或者页面发生了跳转 ( 默认状态下 GetMethod 的实例是自动处理跳转的 ) 等。
 
// 设置成了默认的恢复策略,在发生异常时候将自动重试 3 次,在这里你也可以设置成自定义的恢复策略     getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,     new DefaultHttpMethodRetryHandler()); // 执行 getMethodint
    statusCode = client.executeMethod(getMethod);
    if (statusCode != HttpStatus.SC_OK) {
     System.err.println( "Method failed: " + getMethod.getStatusLine());
        }

 3 、在返回的状态码正确后,即可取得内容。取得目标地址的内容有三种方法:第一种, getResponseBody ,该方法返回的是目标的二进制的 byte 流;第二种, getResponseBodyAsString ,这个方法返回的是 String 类型,值得注意的是该方法返回的 String 的编码是根据系统默认的编码方式。所有返回的 String 值可能编码类型有误,在本文的 字符编码 部分中将对此做详细介绍;第三种, getResponseBodyASStream ,这个方法对于目标地址中又大量数据需要传输是最佳的。在这里我们使用了最简单的 getResponseBody 方法。
byte[] responseBody = method.getResponseBody();
 
释放连接。无论执行方法是否成功,都必须释放连接。
method.releaseConnection();
 
处理内容。在这一步中根据你的需要处理内容,在例子中只是简单的将内容打印到控制台。
System.out.println(new String(responseBody));
下面是程序的完整代码:
 
package test;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
 
public class GetSample{ 
    public static void main(String[] args) { 
       // 构造 HttpClient 的实例  
       HttpClient httpClient = new HttpClient(); 
       // 创建 GET 方法的实例  
       GetMethod getMethod = new GetMethod( "http://www.ibm.com" ); 
       // 使用系统提供的默认的恢复策略
       getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,   
              new DefaultHttpMethodRetryHandler()); 
       try {  
           // 执行 getMethod  
           int statusCode = httpClient.executeMethod(getMethod); 
           if (statusCode != HttpStatus.SC_OK) {
              System.err.println( "Method failed: " + getMethod.getStatusLine());
              }   // 读取内容    
           byte [] responseBody = getMethod.getResponseBody();  
           // 处理内容    System.out.println(new String(responseBody)); 
           } catch (HttpException e) {  
              // 发生致命的异常,可能是协议不对或者返回的内容有问题  
              System.out.println( "Please check your provided http address!" );  
              e.printStackTrace(); } catch (IOException e) {  
                  // 发生网络异常   
                  e.printStackTrace(); }
              finally {  
                  // 释放连接   
                  getMethod.releaseConnection(); } }
    }
       }
    }
}

 

HttpClient 实例:
Tomcat 的各个页面代码:
package com.httptest;
public class JClientLoginTest {
    public static void main(String[] args) throws HttpException, IOException {
       HttpClient client = new HttpClient();
       client.getHostConfiguration().setHost( "127.0.0.1" , 18080, "http" );
HttpMethod method = new GetMethod( "http://localhost:18080/manager/status/index.jsp" );
              // 页面地址
       UsernamePasswordCredentials ups = new UsernamePasswordCredentials(
              "admin" , "admin" );
       client.getState().setCredentials( null , null , ups); // 密码验证
       method.setDoAuthentication( true );
       client.setConnectionTimeout(60000); // 指定查询时间最大值
 
       client.executeMethod(method);
       // 打印服务器返回的状态
 
       System. out .println(method.getStatusLine());
 
       // 打印返回的信息
       String info = method.getResponseBodyAsString();
 
       //     System.out.println(info);
      
       //tomcat 取版本 version
       String version = "" ;
       String[] temp = info.split( "Apache Tomcat/" );
       int i = temp[1].indexOf( "<" );
       version = temp[1].substring(0,i );
       //tomcat 取空闲内存 freeMemory
       String freeMemory = "" ;
       temp = info.split( "Free memory: " );
       i = temp[1].indexOf( "MB" );
       freeMemory = temp[1].substring(0,i)+ "MB" ;
       System. out .println(version+ "," + freeMemory);
       // 释放连接
       method.releaseConnection();
    }
}
Post 方法
根据 RFC2616 ,对 Post 的解释如下: Post 方法用来向目的服务器发出请求,要求它接受被附在请求后的实体,并把它当作请求队列 (Request-Line) 中请求 URI 所指定资源的附加新子项。 POST 被设计成用统一的方法实现下面功能:
1.    对现有资源的注释 ( Annotation of existing resources )
2.    向电子公告栏,新闻组,邮件列表或类似讨论组发送消息
3.    提交数据块,如将表单的结果提交给数据处理过程
4.    通过附加操作来扩展数据库过程
 
调用 HttpClient 中的 PostMethod GetMethod 类似,除了设置 PostMethod 的实例与 GetMethod 有些不同之外,剩下的步骤都差不多。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics