HttpClient使用詳解

Http協議的重要性相信不用我多說了,HttpClient相比傳統JDK自帶的URLConnection,增長了易用性和靈活性(具體區別,往後咱們再討論),它不只是客戶端發送Http請求變得容易,並且也方便了開發人員測試接口(基於Http協議的),即提升了開發的效率,也方便提升代碼的健壯性。所以熟練掌握HttpClient是很重要的必修內容,掌握HttpClient後,相信對於Http協議的瞭解會更加深刻。java

1、簡介

HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,而且它支持HTTP協議最新的版本和建議。HttpClient已經應用在不少的項目中,好比Apache Jakarta上很著名的另外兩個開源項目Cactus和HTMLUnit都使用了HttpClient。apache

下載地址: http://hc.apache.org/downloads.cgi編程

2、特性

1. 基於標準、純淨的java語言。實現了Http1.0和Http1.1服務器

2. 以可擴展的面向對象的結構實現了Http所有的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。cookie

3. 支持HTTPS協議。多線程

4. 經過Http代理創建透明的鏈接。app

5. 利用CONNECT方法經過Http代理創建隧道的https鏈接。socket

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos認證方案。工具

7. 插件式的自定義認證方案。post

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

3、使用方法

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

以上理論資料總結參考:

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

可是上訴地址中的代碼實例並不精簡:

我的整理一份

 結果封裝類 封裝響應的頭部信息、狀態信息、Cookie信息、返回內容
 1  import java.io.BufferedInputStream;  2 import java.io.ByteArrayOutputStream;  3 import java.io.IOException;  4 import java.io.InputStream;  5 import java.util.HashMap;  6 import java.util.zip.GZIPInputStream;  7  8 import org.apache.http.Header;  9 import org.apache.http.HttpEntity;  10 import org.apache.http.util.EntityUtils;  11 import org.apache.log4j.Logger;  12 /**  13  *  14  * 結果封裝類 封裝響應的頭部信息、狀態信息、Cookie信息、返回內容  15  *  16  * @author lishangzhi  17  * E-mail:1669852599@qq.com  18  * @version v1.0  19  * Time:2015年8月1日 上午9:45:33  20 */  21 public class Result {  22 /**  23  * Logger for this class  24 */  25 private static final Logger logger = Logger.getLogger(Result.class);  26  27 private String cookie;  28 private int statusCode;  29 private HashMap<String, Header> headerAll;  30 private HttpEntity httpEntity;  31 private String otherContent;  32  33 /**  34  * 獲取Cookie信息  35  *  36  * @return  37 */  38 public String getCookie() {  39 return cookie;  40  }  41  42 /**  43  * 設置Cookie信息  44  *  45  * @param cookie  46 */  47 public void setCookie(String cookie) {  48 this.cookie = cookie;  49  }  50  51 /**  52  * 獲取結果狀態碼  53  *  54  * @return  55 */  56 public int getStatusCode() {  57 return statusCode;  58  }  59  60 /**  61  * 設置結果狀態碼  62  *  63  * @param statusCode  64 */  65 public void setStatusCode(int statusCode) {  66 this.statusCode = statusCode;  67  }  68  69 /**  70  * 獲取結果頭部信息  71  *  72  * @return  73 */  74 public HashMap<String, Header> getHeaders() {  75 return headerAll;  76  }  77  78 /**  79  * 設置結果頭部信息  80  *  81  * @param headers  82 */  83 public void setHeaders(Header[] headers) {  84 headerAll = new HashMap<String, Header>();  85 for (Header header : headers) {  86  headerAll.put(header.getName(), header);  87  }  88  }  89  90 /**  91  * 獲取響應結果  92  *  93  * @return  94 */  95 public HttpEntity getHttpEntity() {  96 return httpEntity;  97  }  98  99 /** 100  * 設置響應結果 101  * 102  * @param httpEntity 103 */ 104 public void setHttpEntity(HttpEntity httpEntity) { 105 this.httpEntity = httpEntity; 106  } 107 108 /** 109  * 將服務器返回的結果HttpEntity流轉換成String格式的內容 110  * 111  * @param encoding 112  * 指定的轉換編碼 113  * @return 114 */ 115 public String getHtmlContent(String encoding) { 116 // HTML內容 117 if (httpEntity != null) { 118 ByteArrayOutputStream output = new ByteArrayOutputStream(); 119 InputStream is = null; 120 try { 121 if (httpEntity.getContentEncoding() != null 122 && httpEntity.getContentEncoding().getValue().indexOf("gzip") != -1) { 123 // GZIP格式的流解壓 124 is = new GZIPInputStream(new BufferedInputStream(httpEntity.getContent())); 125 } else { 126 is = new BufferedInputStream(httpEntity.getContent()); 127  } 128 String responseContent = ""; 129 if (is != null) { 130 byte[] buffer = new byte[1024]; 131 int n; 132 while ((n = is.read(buffer)) >= 0) { 133 output.write(buffer, 0, n); 134  } 135 responseContent = output.toString(encoding); 136 // responseContent=new 137 // String(responseContent.getBytes("utf-8"),"gbk"); 138  } 139 return responseContent; 140 } catch (IllegalStateException e) { 141  e.printStackTrace(); 142 return ""; 143 } catch (IOException e) { 144  e.printStackTrace(); 145 return ""; 146  } 147 } else { 148 return ""; 149  } 150  } 151 152 /** 153  * 獲取請求中的內容 154 */ 155 public String getHtml(Result result, String chart) { 156 logger.debug("getHtml(Result, String) - start"); //$NON-NLS-1$ 157 158 HttpEntity entity = result.getHttpEntity(); 159 String resultStr = ""; 160 try { 161 resultStr = EntityUtils.toString(entity, chart); 162 } catch (Exception e) { 163 logger.error("getHtml(Result, String)", e); //$NON-NLS-1$ 164 165 // e.printStackTrace(); 166 } finally { 167 try { 168  EntityUtils.consume(entity); 169 } catch (IOException e) { 170 logger.error("getHtml(Result, String)", e); //$NON-NLS-1$ 171 172 // e.printStackTrace(); 173  } 174  } 175 176 logger.debug("getHtml(Result, String) - end"); //$NON-NLS-1$ 177 return resultStr; 178  } 179 180 /** 181  * 關閉HttpEntity流 182 */ 183 public void consume(Result result) { 184 try { 185 HttpEntity entity = result.getHttpEntity(); 186 // EntityUtils.consume(entity); 187 if (entity.isStreaming()) { 188 InputStream instream = entity.getContent(); 189 if (instream != null) { 190  instream.close(); 191  } 192  } 193 } catch (IOException e) { 194  e.printStackTrace(); 195  } 196  } 197 198 public String getOtherContent() { 199 return otherContent; 200  } 201 202 public void setOtherContent(String otherContent) { 203 this.otherContent = otherContent; 204  } 205 }
發送請求 httpclient封裝

 1 import java.io.IOException;  2 import java.util.ArrayList;  3 import java.util.HashMap;  4 import java.util.List;  5 import java.util.Map;  6 import org.apache.http.Header;  7 import org.apache.http.HttpEntity;  8 import org.apache.http.HttpResponse;  9 import org.apache.http.NameValuePair;  10 import org.apache.http.client.ClientProtocolException;  11 import org.apache.http.client.entity.UrlEncodedFormEntity;  12 import org.apache.http.client.methods.HttpGet;  13 import org.apache.http.client.methods.HttpPost;  14 import org.apache.http.cookie.Cookie;  15 import org.apache.http.impl.client.DefaultHttpClient;  16 import org.apache.http.message.BasicHeader;  17 import org.apache.http.message.BasicNameValuePair;  18 /**
 19  *  20  * 發送請求 httpclient封裝  21  *  22  * @author lishangzhi  23  * E-mail:1669852599@qq.com  24  * @version v1.0  25  * Time:2015年8月1日 上午9:46:07  26  */
 27 @SuppressWarnings("deprecation")  28 public class SendRequest {  29 
 30     private static DefaultHttpClient client = new DefaultHttpClient();  31 
 32     /**
 33  * 發送Get請求  34  *  35  * @param url  36  * 請求的地址  37  * @param headers  38  * 請求的頭部信息  39  * @param params  40  * 請求的參數  41  * @param encoding  42  * 字符編碼  43  * @return
 44  * @throws ClientProtocolException  45  * @throws IOException  46      */
 47     public static Result sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding,  48             boolean duan) throws ClientProtocolException, IOException {  49         url = url + (null == params ? "" : assemblyParameter(params));  50         HttpGet hp = new HttpGet(url);  51         if (null != headers)  52  hp.setHeaders(assemblyHeader(headers));  53         HttpResponse response = client.execute(hp);  54         if (duan)  55  hp.abort();  56         HttpEntity entity = response.getEntity();  57         Result result = new Result();  58  result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));  59  result.setStatusCode(response.getStatusLine().getStatusCode());  60  result.setHeaders(response.getAllHeaders());  61  result.setHttpEntity(entity);  62         return result;  63  }  64 
 65     public static Result sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding)  66             throws ClientProtocolException, IOException {  67         return sendGet(url, headers, params, encoding, false);  68  }  69 
 70     /**
 71  * 發送Post請求  72  *  73  * @param url  74  * 請求的地址  75  * @param headers  76  * 請求的頭部信息  77  * @param params  78  * 請求的參數  79  * @param encoding  80  * 字符編碼  81  * @return
 82  * @throws ClientProtocolException  83  * @throws IOException  84      */
 85     public static Result sendPost(String url, Map<String, String> headers, Map<String, String> params, String encoding)  86             throws ClientProtocolException, IOException {  87         HttpPost post = new HttpPost(url);  88 
 89         List<NameValuePair> list = new ArrayList<NameValuePair>();  90         for (String temp : params.keySet()) {  91             list.add(new BasicNameValuePair(temp, params.get(temp)));  92  }  93         post.setEntity(new UrlEncodedFormEntity(list, encoding));  94 
 95         if (null != headers)  96  post.setHeaders(assemblyHeader(headers));  97         HttpResponse response = client.execute(post);  98         HttpEntity entity = response.getEntity();  99 
100         Result result = new Result(); 101  result.setStatusCode(response.getStatusLine().getStatusCode()); 102  result.setHeaders(response.getAllHeaders()); 103  result.setCookie(assemblyCookie(client.getCookieStore().getCookies())); 104  result.setHttpEntity(entity); 105         return result; 106  } 107 
108     /**
109  * 組裝頭部信息 110  * 111  * @param headers 112  * @return
113      */
114     public static Header[] assemblyHeader(Map<String, String> headers) { 115         Header[] allHeader = new BasicHeader[headers.size()]; 116         int i = 0; 117         for (String str : headers.keySet()) { 118             allHeader[i] = new BasicHeader(str, headers.get(str)); 119             i++; 120  } 121         return allHeader; 122  } 123 
124     /**
125  * 組裝Cookie 126  * 127  * @param cookies 128  * @return
129      */
130     public static String assemblyCookie(List<Cookie> cookies) { 131         StringBuffer sbu = new StringBuffer(); 132         for (Cookie cookie : cookies) { 133             sbu.append(cookie.getName()).append("=").append(cookie.getValue()).append(";"); 134  } 135         if (sbu.length() > 0) 136             sbu.deleteCharAt(sbu.length() - 1); 137         return sbu.toString(); 138  } 139 
140     /**
141  * 組裝請求參數 142  * 143  * @param parameters 144  * @return
145      */
146     public static String assemblyParameter(Map<String, String> parameters) { 147         String para = "?"; 148         for (String str : parameters.keySet()) { 149             para += str + "=" + parameters.get(str) + "&"; 150  } 151         return para.substring(0, para.length() - 1); 152  } 153 
154     // TODO demo
155     public static void main(String[] args) { 156         Map<String, String> param = new HashMap<String, String>(); 157         try { 158             Result result = SendRequest.sendGet("http://www.baidu.com", param, param, "utf-8"); 159             // SendRequest.u
160             String str = result.getHtml(result, "utf-8"); 161  System.out.println(str); 162         } catch (Exception e) { 163  e.printStackTrace(); 164  } 165  } 166 
167 }
測試案例:
 1 // TODO demo
 2     public static void main(String[] args) {  3         Map<String, String> param = new HashMap<String, String>();  4         try {  5             Result result = SendRequest.sendGet("http://www.baidu.com", param, param, "utf-8");  6             // SendRequest.u
 7             String str = result.getHtml(result, "utf-8");  8  System.out.println(str);  9         } catch (Exception e) { 10  e.printStackTrace(); 11  } 12     }
返回結果:

相關文章
相關標籤/搜索