HttpClient使用总结

来源:互联网 发布:广东省干部网络学校 编辑:程序博客网 时间:2024/06/06 12:48

 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

  

使用 HttpClient 需要以下 6 个步骤:

1. 创建 HttpClient 的实例

2. 创建某种连接方法的实例,支持get和post方式,分别是 GetMethod、PostMethod。

3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

4. 读 response

5. 释放连接。无论执行方法是否成功,都必须释放连接

6. 对得到后的内容进行处理

   根据以上步骤,我们来编写用GET方法来取得某网页内容的代码。

   创建 HttpClient对象, HttpClient client = new HttpClient();

   client.getHttpConnectionManager().getParams().setConnectionTimeout(300000);   设置请求超时时间。

   GetMethod gm = new GetMethod();

  URI uri=new URI(url,false);//设置请求资源,false表示不检测url格式。
     gm.setURI(uri);
      gm.setFollowRedirects(false);//不自动跳转

      gm.setQueryString(new NameValuePair[] {
                        new NameValuePair("name",“张三”),
                        new NameValuePair("type",1) });

  int retCode= client.executeMethod(gm);//得到请求返回值
            gm.releaseConnection();//关闭

//重定向处理

if ((retCode == HttpStatus.SC_MOVED_TEMPORARILY) || (retCode == HttpStatus.SC_MOVED_PERMANENTLY) || (retCode == HttpStatus.SC_SEE_OTHER) || (retCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                // 读取新的 URL 地址
                   Header header=gm.getResponseHeader("location");
                   if (header!=null){
                      String newuri=header.getValue();
                      if((newuri==null)||(newuri.equals("")))
                         newuri="/";
                         URI newUrl=new URI(newuri,false);
                         GetMethod redirect=new GetMethod();
                         redirect.setURI(newUrl);
                         retCode=client.executeMethod(redirect);
                         log.info("Redirect:"+redirect.getStatusLine().toString());
                         redirect.releaseConnection();
                   }
                }