欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HttpClient 在Java项目中的使用详解

程序员文章站 2024-03-06 13:11:32
http协议的重要性相信不用我多说了,httpclient相比传统jdk自带的urlconnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发...

http协议的重要性相信不用我多说了,httpclient相比传统jdk自带的urlconnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送http请求变得容易,而且也方便了开发人员测试接口(基于http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握httpclient是很重要的必修内容,掌握httpclient后,相信对于http协议的了解会更加深入。

一、简介

httpclient是apache jakarta common下的子项目,用来提供高效的、最新的、功能丰富的支持http协议的客户端编程工具包,并且它支持http协议最新的版本和建议。httpclient已经应用在很多的项目中,比如apache jakarta上很著名的另外两个开源项目cactus和htmlunit都使用了httpclient。

下载地址:

二、特性

1. 基于标准、纯净的java语言。实现了http1.0和http1.1
2. 以可扩展的面向对象的结构实现了http全部的方法(get, post, put, delete, head, options, and trace)。
3. 支持https协议。
4. 通过http代理建立透明的连接。
5. 利用connect方法通过http代理建立隧道的https连接。
6. basic, digest, ntlmv1, ntlmv2, ntlm2 session, snpnego/kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理set-cookie中的cookie。
11. 插件式的自定义cookie策略。
12. request的输出流可以避免流中内容直接缓冲到socket服务器。
13. response的输入流可以有效的从socket服务器直接读取相应内容。
14. 在http1.0和http1.1中利用keepalive保持持久连接。
15. 直接获取服务器发送的response code和 headers。
16. 设置连接超时的能力。
17. 实验性的支持http1.1 response caching。
18. 源代码基于apache license 可免费获取。

三、使用方法

使用httpclient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建httpclient对象。

2. 创建请求方法的实例,并指定请求url。如果需要发送get请求,创建httpget对象;如果需要发送post请求,创建httppost对象。

3. 如果需要发送请求参数,可调用httpget、httppost共同的setparams(hetpparams params)方法来添加请求参数;对于httppost对象而言,也可调用setentity(httpentity entity)方法来设置请求参数。

4. 调用httpclient对象的execute(httpurirequest request)发送请求,该方法返回一个httpresponse。

5. 调用httpresponse的getallheaders()、getheaders(string name)等方法可获取服务器的响应头;调用httpresponse的getentity()方法可获取httpentity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

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

四、实例

package com.test; 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.ioexception; 
import java.io.unsupportedencodingexception; 
import java.security.keymanagementexception; 
import java.security.keystore; 
import java.security.keystoreexception; 
import java.security.nosuchalgorithmexception; 
import java.security.cert.certificateexception; 
import java.util.arraylist; 
import java.util.list; 
import javax.net.ssl.sslcontext; 
import org.apache.http.httpentity; 
import org.apache.http.namevaluepair; 
import org.apache.http.parseexception; 
import org.apache.http.client.clientprotocolexception; 
import org.apache.http.client.entity.urlencodedformentity; 
import org.apache.http.client.methods.closeablehttpresponse; 
import org.apache.http.client.methods.httpget; 
import org.apache.http.client.methods.httppost; 
import org.apache.http.conn.ssl.sslconnectionsocketfactory; 
import org.apache.http.conn.ssl.sslcontexts; 
import org.apache.http.conn.ssl.trustselfsignedstrategy; 
import org.apache.http.entity.contenttype; 
import org.apache.http.entity.mime.multipartentitybuilder; 
import org.apache.http.entity.mime.content.filebody; 
import org.apache.http.entity.mime.content.stringbody; 
import org.apache.http.impl.client.closeablehttpclient; 
import org.apache.http.impl.client.httpclients; 
import org.apache.http.message.basicnamevaluepair; 
import org.apache.http.util.entityutils; 
import org.junit.test; 
public class httpclienttest { 
  @test 
  public void junittest() { 
    get(); 
  } 
  /** 
   * httpclient连接ssl 
   */ 
  public void ssl() { 
    closeablehttpclient httpclient = null; 
    try { 
      keystore truststore = keystore.getinstance(keystore.getdefaulttype()); 
      fileinputstream instream = new fileinputstream(new file("d:\\tomcat.keystore")); 
      try { 
        // 加载keystore d:\\tomcat.keystore  
        truststore.load(instream, "123456".tochararray()); 
      } catch (certificateexception e) { 
        e.printstacktrace(); 
      } finally { 
        try { 
          instream.close(); 
        } catch (exception ignore) { 
        } 
      } 
      // 相信自己的ca和所有自签名的证书 
      sslcontext sslcontext = sslcontexts.custom().loadtrustmaterial(truststore, new trustselfsignedstrategy()).build(); 
      // 只允许使用tlsv1协议 
      sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory(sslcontext, new string[] { "tlsv1" }, null, 
          sslconnectionsocketfactory.browser_compatible_hostname_verifier); 
      httpclient = httpclients.custom().setsslsocketfactory(sslsf).build(); 
      // 创建http请求(get方式) 
      httpget httpget = new httpget("https://localhost:8443/mydemo/ajax/serivcej.action"); 
      system.out.println("executing request" + httpget.getrequestline()); 
      closeablehttpresponse response = httpclient.execute(httpget); 
      try { 
        httpentity entity = response.getentity(); 
        system.out.println("----------------------------------------"); 
        system.out.println(response.getstatusline()); 
        if (entity != null) { 
          system.out.println("response content length: " + entity.getcontentlength()); 
          system.out.println(entityutils.tostring(entity)); 
          entityutils.consume(entity); 
        } 
      } finally { 
        response.close(); 
      } 
    } catch (parseexception e) { 
      e.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } catch (keymanagementexception e) { 
      e.printstacktrace(); 
    } catch (nosuchalgorithmexception e) { 
      e.printstacktrace(); 
    } catch (keystoreexception e) { 
      e.printstacktrace(); 
    } finally { 
      if (httpclient != null) { 
        try { 
          httpclient.close(); 
        } catch (ioexception e) { 
          e.printstacktrace(); 
        } 
      } 
    } 
  } 
  /** 
   * post方式提交表单(模拟用户登录请求) 
   */ 
  public void postform() { 
    // 创建默认的httpclient实例.  
    closeablehttpclient httpclient = httpclients.createdefault(); 
    // 创建httppost  
    httppost httppost = new httppost("http://localhost:8080/mydemo/ajax/serivcej.action"); 
    // 创建参数队列  
    list<namevaluepair> formparams = new arraylist<namevaluepair>(); 
    formparams.add(new basicnamevaluepair("username", "admin")); 
    formparams.add(new basicnamevaluepair("password", "123456")); 
    urlencodedformentity uefentity; 
    try { 
      uefentity = new urlencodedformentity(formparams, "utf-8"); 
      httppost.setentity(uefentity); 
      system.out.println("executing request " + httppost.geturi()); 
      closeablehttpresponse response = httpclient.execute(httppost); 
      try { 
        httpentity entity = response.getentity(); 
        if (entity != null) { 
          system.out.println("--------------------------------------"); 
          system.out.println("response content: " + entityutils.tostring(entity, "utf-8")); 
          system.out.println("--------------------------------------"); 
        } 
      } finally { 
        response.close(); 
      } 
    } catch (clientprotocolexception e) { 
      e.printstacktrace(); 
    } catch (unsupportedencodingexception e1) { 
      e1.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      // 关闭连接,释放资源  
      try { 
        httpclient.close(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
  } 
  /** 
   * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
   */ 
  public void post() { 
    // 创建默认的httpclient实例.  
    closeablehttpclient httpclient = httpclients.createdefault(); 
    // 创建httppost  
    httppost httppost = new httppost("http://localhost:8080/mydemo/ajax/serivcej.action"); 
    // 创建参数队列  
    list<namevaluepair> formparams = new arraylist<namevaluepair>(); 
    formparams.add(new basicnamevaluepair("type", "house")); 
    urlencodedformentity uefentity; 
    try { 
      uefentity = new urlencodedformentity(formparams, "utf-8"); 
      httppost.setentity(uefentity); 
      system.out.println("executing request " + httppost.geturi()); 
      closeablehttpresponse response = httpclient.execute(httppost); 
      try { 
        httpentity entity = response.getentity(); 
        if (entity != null) { 
          system.out.println("--------------------------------------"); 
          system.out.println("response content: " + entityutils.tostring(entity, "utf-8")); 
          system.out.println("--------------------------------------"); 
        } 
      } finally { 
        response.close(); 
      } 
    } catch (clientprotocolexception e) { 
      e.printstacktrace(); 
    } catch (unsupportedencodingexception e1) { 
      e1.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      // 关闭连接,释放资源  
      try { 
        httpclient.close(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
  } 
  /** 
   * 发送 get请求 
   */ 
  public void get() { 
    closeablehttpclient httpclient = httpclients.createdefault(); 
    try { 
      // 创建httpget.  
      httpget httpget = new httpget("http://www.baidu.com/"); 
      system.out.println("executing request " + httpget.geturi()); 
      // 执行get请求.  
      closeablehttpresponse response = httpclient.execute(httpget); 
      try { 
        // 获取响应实体  
        httpentity entity = response.getentity(); 
        system.out.println("--------------------------------------"); 
        // 打印响应状态  
        system.out.println(response.getstatusline()); 
        if (entity != null) { 
          // 打印响应内容长度  
          system.out.println("response content length: " + entity.getcontentlength()); 
          // 打印响应内容  
          system.out.println("response content: " + entityutils.tostring(entity)); 
        } 
        system.out.println("------------------------------------"); 
      } finally { 
        response.close(); 
      } 
    } catch (clientprotocolexception e) { 
      e.printstacktrace(); 
    } catch (parseexception e) { 
      e.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      // 关闭连接,释放资源  
      try { 
        httpclient.close(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
  } 
  /** 
   * 上传文件 
   */ 
  public void upload() { 
    closeablehttpclient httpclient = httpclients.createdefault(); 
    try { 
      httppost httppost = new httppost("http://localhost:8080/mydemo/ajax/serivcefile.action"); 
      filebody bin = new filebody(new file("f:\\image\\sendpix0.jpg")); 
      stringbody comment = new stringbody("a binary file of some kind", contenttype.text_plain); 
      httpentity reqentity = multipartentitybuilder.create().addpart("bin", bin).addpart("comment", comment).build(); 
      httppost.setentity(reqentity); 
      system.out.println("executing request " + httppost.getrequestline()); 
      closeablehttpresponse response = httpclient.execute(httppost); 
      try { 
        system.out.println("----------------------------------------"); 
        system.out.println(response.getstatusline()); 
        httpentity resentity = response.getentity(); 
        if (resentity != null) { 
          system.out.println("response content length: " + resentity.getcontentlength()); 
        } 
        entityutils.consume(resentity); 
      } finally { 
        response.close(); 
      } 
    } catch (clientprotocolexception e) { 
      e.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      try { 
        httpclient.close(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
  } 
}
</namevaluepair></namevaluepair>
</namevaluepair></namevaluepair> 

本实例是采用httpclient4.3最新版本。该版本与之前的代码写法风格相差较大,大家多留意下。