HttpClient详解

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

一、简介

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

下载地址: http://hc.apache.org/downloads.cgi

二、特性

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. 释放连接。无论执行方法是否成功,都必须释放连接



  1. public class HttpClientTest {  
  2.   
  3.     @Test  
  4.     public void jUnitTest() {  
  5.         get();  
  6.     }  
  7.   
  8.     /** 
  9.      * HttpClient连接SSL 
  10.      */  
  11.     public void ssl() {  
  12.         CloseableHttpClient httpclient = null;  
  13.         try {  
  14.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  15.             FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));  
  16.             try {  
  17.                 // 加载keyStore d:\\tomcat.keystore    
  18.                 trustStore.load(instream, "123456".toCharArray());  
  19.             } catch (CertificateException e) {  
  20.                 e.printStackTrace();  
  21.             } finally {  
  22.                 try {  
  23.                     instream.close();  
  24.                 } catch (Exception ignore) {  
  25.                 }  
  26.             }  
  27.             // 相信自己的CA和所有自签名的证书  
  28.             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
  29.             // 只允许使用TLSv1协议  
  30.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
  31.                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
  32.             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
  33.             // 创建http请求(get方式)  
  34.             HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");  
  35.             System.out.println("executing request" + httpget.getRequestLine());  
  36.             CloseableHttpResponse response = httpclient.execute(httpget);  
  37.             try {  
  38.                 HttpEntity entity = response.getEntity();  
  39.                 System.out.println("----------------------------------------");  
  40.                 System.out.println(response.getStatusLine());  
  41.                 if (entity != null) {  
  42.                     System.out.println("Response content length: " + entity.getContentLength());  
  43.                     System.out.println(EntityUtils.toString(entity));  
  44.                     EntityUtils.consume(entity);  
  45.                 }  
  46.             } finally {  
  47.                 response.close();  
  48.             }  
  49.         } catch (ParseException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         } catch (KeyManagementException e) {  
  54.             e.printStackTrace();  
  55.         } catch (NoSuchAlgorithmException e) {  
  56.             e.printStackTrace();  
  57.         } catch (KeyStoreException e) {  
  58.             e.printStackTrace();  
  59.         } finally {  
  60.             if (httpclient != null) {  
  61.                 try {  
  62.                     httpclient.close();  
  63.                 } catch (IOException e) {  
  64.                     e.printStackTrace();  
  65.                 }  
  66.             }  
  67.         }  
  68.     }  
  69.   
  70.     /** 
  71.      * post方式提交表单(模拟用户登录请求) 
  72.      */  
  73.     public void postForm() {  
  74.         // 创建默认的httpClient实例.    
  75.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  76.         // 创建httppost    
  77.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
  78.         // 创建参数队列    
  79.         List formparams = new ArrayList();  
  80.         formparams.add(new BasicNameValuePair("username""admin"));  
  81.         formparams.add(new BasicNameValuePair("password""123456"));  
  82.         UrlEncodedFormEntity uefEntity;  
  83.         try {  
  84.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  85.             httppost.setEntity(uefEntity);  
  86.             System.out.println("executing request " + httppost.getURI());  
  87.             CloseableHttpResponse response = httpclient.execute(httppost);  
  88.             try {  
  89.                 HttpEntity entity = response.getEntity();  
  90.                 if (entity != null) {  
  91.                     System.out.println("--------------------------------------");  
  92.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
  93.                     System.out.println("--------------------------------------");  
  94.                 }  
  95.             } finally {  
  96.                 response.close();  
  97.             }  
  98.         } catch (ClientProtocolException e) {  
  99.             e.printStackTrace();  
  100.         } catch (UnsupportedEncodingException e1) {  
  101.             e1.printStackTrace();  
  102.         } catch (IOException e) {  
  103.             e.printStackTrace();  
  104.         } finally {  
  105.             // 关闭连接,释放资源    
  106.             try {  
  107.                 httpclient.close();  
  108.             } catch (IOException e) {  
  109.                 e.printStackTrace();  
  110.             }  
  111.         }  
  112.     }  
  113.   
  114.     /** 
  115.      * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
  116.      */  
  117.     public void post() {  
  118.         // 创建默认的httpClient实例.    
  119.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  120.         // 创建httppost    
  121.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
  122.         // 创建参数队列    
  123.         List formparams = new ArrayList();  
  124.         formparams.add(new BasicNameValuePair("type""house"));  
  125.         UrlEncodedFormEntity uefEntity;  
  126.         try {  
  127.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  128.             httppost.setEntity(uefEntity);  
  129.             System.out.println("executing request " + httppost.getURI());  
  130.             CloseableHttpResponse response = httpclient.execute(httppost);  
  131.             try {  
  132.                 HttpEntity entity = response.getEntity();  
  133.                 if (entity != null) {  
  134.                     System.out.println("--------------------------------------");  
  135.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
  136.                     System.out.println("--------------------------------------");  
  137.                 }  
  138.             } finally {  
  139.                 response.close();  
  140.             }  
  141.         } catch (ClientProtocolException e) {  
  142.             e.printStackTrace();  
  143.         } catch (UnsupportedEncodingException e1) {  
  144.             e1.printStackTrace();  
  145.         } catch (IOException e) {  
  146.             e.printStackTrace();  
  147.         } finally {  
  148.             // 关闭连接,释放资源    
  149.             try {  
  150.                 httpclient.close();  
  151.             } catch (IOException e) {  
  152.                 e.printStackTrace();  
  153.             }  
  154.         }  
  155.     }  
  156.   
  157.     /** 
  158.      * 发送 get请求 
  159.      */  
  160.     public void get() {  
  161.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  162.         try {  
  163.             // 创建httpget.    
  164.             HttpGet httpget = new HttpGet("http://www.baidu.com/");  
  165.             System.out.println("executing request " + httpget.getURI());  
  166.             // 执行get请求.    
  167.             CloseableHttpResponse response = httpclient.execute(httpget);  
  168.             try {  
  169.                 // 获取响应实体    
  170.                 HttpEntity entity = response.getEntity();  
  171.                 System.out.println("--------------------------------------");  
  172.                 // 打印响应状态    
  173.                 System.out.println(response.getStatusLine());  
  174.                 if (entity != null) {  
  175.                     // 打印响应内容长度    
  176.                     System.out.println("Response content length: " + entity.getContentLength());  
  177.                     // 打印响应内容    
  178.                     System.out.println("Response content: " + EntityUtils.toString(entity));  
  179.                 }  
  180.                 System.out.println("------------------------------------");  
  181.             } finally {  
  182.                 response.close();  
  183.             }  
  184.         } catch (ClientProtocolException e) {  
  185.             e.printStackTrace();  
  186.         } catch (ParseException e) {  
  187.             e.printStackTrace();  
  188.         } catch (IOException e) {  
  189.             e.printStackTrace();  
  190.         } finally {  
  191.             // 关闭连接,释放资源    
  192.             try {  
  193.                 httpclient.close();  
  194.             } catch (IOException e) {  
  195.                 e.printStackTrace();  
  196.             }  
  197.         }  
  198.     }  
  199.   
  200.     /** 
  201.      * 上传文件 
  202.      */  
  203.     public void upload() {  
  204.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  205.         try {  
  206.             HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");  
  207.   
  208.             FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));  
  209.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
  210.   
  211.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
  212.   
  213.             httppost.setEntity(reqEntity);  
  214.   
  215.             System.out.println("executing request " + httppost.getRequestLine());  
  216.             CloseableHttpResponse response = httpclient.execute(httppost);  
  217.             try {  
  218.                 System.out.println("----------------------------------------");  
  219.                 System.out.println(response.getStatusLine());  
  220.                 HttpEntity resEntity = response.getEntity();  
  221.                 if (resEntity != null) {  
  222.                     System.out.println("Response content length: " + resEntity.getContentLength());  
  223.                 }  
  224.                 EntityUtils.consume(resEntity);  
  225.             } finally {  
  226.                 response.close();  
  227.             }  
  228.         } catch (ClientProtocolException e) {  
  229.             e.printStackTrace();  
  230.         } catch (IOException e) {  
  231.             e.printStackTrace();  
  232.         } finally {  
  233.             try {  
  234.                 httpclient.close();  
  235.             } catch (IOException e) {  
  236.                 e.printStackTrace();  
  237.             }  
  238.         }  
  239.     }  
  240. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值