Apache HttpClient使用詳解

轉載地址:http://eksliang.iteye.com/blog/2191017


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 可免費獲取

 

三、使用方法

       Mavn座標

Java代碼  收藏代碼
  1. <dependency>  
  2.     <groupId>org.apache.httpcomponents</groupId>  
  3.     <artifactId>httpclient</artifactId>  
  4.     <version>4.3.4</version>  
  5. </dependency>  

 

使用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. 釋放連接。無論執行方法是否成功,都必須釋放連接

 

 

四.post跟get請求示例
Java代碼  收藏代碼
  1. package com.ickes;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  8. import org.apache.http.client.methods.CloseableHttpResponse;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.entity.StringEntity;  
  12. import org.apache.http.impl.client.CloseableHttpClient;  
  13. import org.apache.http.impl.client.HttpClients;  
  14. import org.apache.http.message.BasicNameValuePair;  
  15. import org.apache.http.protocol.HTTP;  
  16. import org.apache.http.util.EntityUtils;  
  17.   
  18. public class HttpClientDemo {  
  19.       
  20.     public static void main(String[] args) throws Exception  {   
  21.         get();  
  22.     }  
  23.       
  24.     /** 
  25.      * post方式提交json代碼 
  26.      * @throws Exception  
  27.      */  
  28.     public static void postJson() throws Exception{  
  29.         //創建默認的httpClient實例.   
  30.         CloseableHttpClient httpclient = null;  
  31.         //接收響應結果  
  32.         CloseableHttpResponse response = null;  
  33.         try {  
  34.             //創建httppost  
  35.             httpclient = HttpClients.createDefault();    
  36.             String url ="http://192.168.16.36:8081/goSearch/gosuncn/deleteDocs.htm";  
  37.             HttpPost httpPost = new HttpPost(url);  
  38.             httpPost.addHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded");  
  39.             //參數  
  40.             String json ="{'ids':['html1','html2']}";  
  41.             StringEntity se = new StringEntity(json);  
  42.             se.setContentEncoding("UTF-8");  
  43.             se.setContentType("application/json");//發送json需要設置contentType  
  44.             httpPost.setEntity(se);  
  45.             response = httpclient.execute(httpPost);  
  46.             //解析返結果  
  47.             HttpEntity entity = response.getEntity();   
  48.             if(entity != null){  
  49.                 String resStr = EntityUtils.toString(entity, "UTF-8");      
  50.                 System.out.println(resStr);  
  51.             }  
  52.         } catch (Exception e) {  
  53.             throw e;  
  54.         }finally{  
  55.             httpclient.close();  
  56.             response.close();  
  57.         }  
  58.     }  
  59.       
  60.      /**  
  61.      * post方式提交表單(模擬用戶登錄請求)  
  62.      * @throws Exception  
  63.      */    
  64.     public static void postForm() throws Exception  {    
  65.         // 創建默認的httpClient實例.      
  66.         CloseableHttpClient httpclient = null;  
  67.         //發送請求  
  68.         CloseableHttpResponse response = null;  
  69.         try {  
  70.             httpclient = HttpClients.createDefault();    
  71.             // 創建httppost      
  72.             String url= "http://localhost:8080/search/ajx/user.htm";  
  73.             HttpPost httppost = new HttpPost(url);    
  74.             // 創建參數隊列      
  75.             List<NameValuePair> formparams = new ArrayList<NameValuePair>();    
  76.             formparams.add(new BasicNameValuePair("username""admin"));    
  77.             formparams.add(new BasicNameValuePair("password""123456"));  
  78.             //參數轉碼  
  79.             UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");    
  80.             httppost.setEntity(uefEntity);   
  81.             response = httpclient.execute(httppost);    
  82.             HttpEntity entity = response.getEntity();    
  83.             if (entity != null) {    
  84.                   System.out.println(EntityUtils.toString(entity, "UTF-8"));    
  85.             }    
  86.             //釋放連接  
  87.         } catch (Exception e) {  
  88.             throw e;  
  89.         }finally{  
  90.              httpclient.close();  
  91.              response.close();  
  92.         }  
  93.     }    
  94.       
  95.     /**  
  96.      * 發送 get請求  
  97.      * @throws Exception  
  98.      */    
  99.     public static void get() throws Exception {    
  100.         CloseableHttpClient httpclient = null;  
  101.         CloseableHttpResponse response = null;  
  102.         try {  
  103.             httpclient = HttpClients.createDefault();    
  104.             // 創建httpget.      
  105.             HttpGet httpget = new HttpGet("http://www.baidu.com/");    
  106.             // 執行get請求.      
  107.             response = httpclient.execute(httpget);    
  108.             // 獲取響應實體      
  109.             HttpEntity entity = response.getEntity();    
  110.         
  111.             // 打印響應狀態      
  112.             System.out.println(response.getStatusLine().getStatusCode());    
  113.             if (entity != null) {    
  114.                 // 打印響應內容      
  115.                 System.out.println("Response content: " + EntityUtils.toString(entity));    
  116.             }  
  117.         } catch (Exception e) {  
  118.             throw e;  
  119.         }finally{  
  120.             httpclient.close();  
  121.             response.close();  
  122.         }  
  123.     }  
  124. }  

 

 

五、SSL跟上傳文件實例

 

Java代碼  收藏代碼
  1. package com.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.security.KeyManagementException;  
  8. import java.security.KeyStore;  
  9. import java.security.KeyStoreException;  
  10. import java.security.NoSuchAlgorithmException;  
  11. import java.security.cert.CertificateException;  
  12. import java.util.ArrayList;  
  13. import java.util.List;  
  14. import javax.net.ssl.SSLContext;  
  15. import org.apache.http.HttpEntity;  
  16. import org.apache.http.NameValuePair;  
  17. import org.apache.http.ParseException;  
  18. import org.apache.http.client.ClientProtocolException;  
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  20. import org.apache.http.client.methods.CloseableHttpResponse;  
  21. import org.apache.http.client.methods.HttpGet;  
  22. import org.apache.http.client.methods.HttpPost;  
  23. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  24. import org.apache.http.conn.ssl.SSLContexts;  
  25. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;  
  26. import org.apache.http.entity.ContentType;  
  27. import org.apache.http.entity.mime.MultipartEntityBuilder;  
  28. import org.apache.http.entity.mime.content.FileBody;  
  29. import org.apache.http.entity.mime.content.StringBody;  
  30. import org.apache.http.impl.client.CloseableHttpClient;  
  31. import org.apache.http.impl.client.HttpClients;  
  32. import org.apache.http.message.BasicNameValuePair;  
  33. import org.apache.http.util.EntityUtils;  
  34. import org.junit.Test;  
  35.   
  36. public class HttpClientTest {  
  37.   
  38.     @Test  
  39.     public void jUnitTest() {  
  40.         ssl();  
  41.     }  
  42.   
  43.     /** 
  44.      * HttpClient連接SSL 
  45.      */  
  46.     public void ssl() {  
  47.         CloseableHttpClient httpclient = null;  
  48.         try {  
  49.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  50.             FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));  
  51.             try {  
  52.                 // 加載keyStore d:\\tomcat.keystore    
  53.                 trustStore.load(instream, "123456".toCharArray());  
  54.             } catch (CertificateException e) {  
  55.                 e.printStackTrace();  
  56.             } finally {  
  57.                 try {  
  58.                     instream.close();  
  59.                 } catch (Exception ignore) {  
  60.                 }  
  61.             }  
  62.             // 相信自己的CA和所有自簽名的證書  
  63.             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
  64.             // 只允許使用TLSv1協議  
  65.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
  66.                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
  67.             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
  68.             // 創建http請求(get方式)  
  69.             HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");  
  70.             System.out.println("executing request" + httpget.getRequestLine());  
  71.             CloseableHttpResponse response = httpclient.execute(httpget);  
  72.             try {  
  73.                 HttpEntity entity = response.getEntity();  
  74.                 System.out.println("----------------------------------------");  
  75.                 System.out.println(response.getStatusLine());  
  76.                 if (entity != null) {  
  77.                     System.out.println("Response content length: " + entity.getContentLength());  
  78.                     System.out.println(EntityUtils.toString(entity));  
  79.                     EntityUtils.consume(entity);  
  80.                 }  
  81.             } finally {  
  82.                 response.close();  
  83.             }  
  84.         } catch (ParseException e) {  
  85.             e.printStackTrace();  
  86.         } catch (IOException e) {  
  87.             e.printStackTrace();  
  88.         } catch (KeyManagementException e) {  
  89.             e.printStackTrace();  
  90.         } catch (NoSuchAlgorithmException e) {  
  91.             e.printStackTrace();  
  92.         } catch (KeyStoreException e) {  
  93.             e.printStackTrace();  
  94.         } finally {  
  95.             if (httpclient != null) {  
  96.                 try {  
  97.                     httpclient.close();  
  98.                 } catch (IOException e) {  
  99.                     e.printStackTrace();  
  100.                 }  
  101.             }  
  102.         }  
  103.     }  
  104.   
  105.     /** 
  106.      * 上傳文件 
  107.      */  
  108.     public void upload() {  
  109.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  110.         try {  
  111.             HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");  
  112.   
  113.             FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));  
  114.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
  115.   
  116.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
  117.   
  118.             httppost.setEntity(reqEntity);  
  119.   
  120.             System.out.println("executing request " + httppost.getRequestLine());  
  121.             CloseableHttpResponse response = httpclient.execute(httppost);  
  122.             try {  
  123.                 System.out.println("----------------------------------------");  
  124.                 System.out.println(response.getStatusLine());  
  125.                 HttpEntity resEntity = response.getEntity();  
  126.                 if (resEntity != null) {  
  127.                     System.out.println("Response content length: " + resEntity.getContentLength());  
  128.                 }  
  129.                 EntityUtils.consume(resEntity);  
  130.             } finally {  
  131.                 response.close();  
  132.             }  
  133.         } catch (ClientProtocolException e) {  
  134.             e.printStackTrace();  
  135.         } catch (IOException e) {  
  136.             e.printStackTrace();  
  137.         } finally {  
  138.             try {  
  139.                 httpclient.close();  
  140.             } catch (IOException e) {  
  141.                 e.printStackTrace();  
  142.             }  
  143.         }  
  144.     }  
  145. }  

   本實例是採用HttpClient4.3最新版本。該版本與之前的代碼寫法風格相差較大,大家多留意下。

 

參考:http://blog.csdn.net/wangpeng047/article/details/19624529

發佈了49 篇原創文章 · 獲贊 37 · 訪問量 40萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章