Http協議的重要性相信不用我多說了,HttpClient相比傳統JDK自帶的URLConnection,增長了易用性和靈活性(具體區別,往後咱們再討論),它不只是客戶端發送Http請求變得容易,並且也方便了開發人員測試接口(基於Http協議的),即提升了開發的效率,也方便提升代碼的健壯性。所以熟練掌握HttpClient是很重要的必修內容,掌握HttpClient後,相信對於Http協議的瞭解會更加深刻。java
HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,而且它支持HTTP協議最新的版本和建議。HttpClient已經應用在不少的項目中,好比Apache Jakarta上很著名的另外兩個開源項目Cactus和HTMLUnit都使用了HttpClient。apache
下載地址: http://hc.apache.org/downloads.cgi編程
1. 基於標準、純淨的Java語言。實現了Http1.0和Http1.1服務器
2. 以可擴展的面向對象的結構實現了Http所有的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。多線程
3. 支持HTTPS協議。app
4. 經過Http代理創建透明的鏈接。socket
5. 利用CONNECT方法經過Http代理創建隧道的https鏈接。ide
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 可免費獲取。
使用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. 釋放鏈接。不管執行方法是否成功,都必須釋放鏈接
所需JAR
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
package cn.com.demo; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; 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.DefaultHostnameVerifier; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; 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; public class HttpClientUtil { private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000) .setConnectionRequestTimeout(15000).build(); // 單例模式 private static HttpClientUtil instance = null; private HttpClientUtil() { } public static HttpClientUtil getInstance() { if (instance == null) { instance = new HttpClientUtil(); } return instance; } /** * 發送 post請求 * * @param httpUrl * 地址 */ public String sendHttpPost(String httpUrl) { HttpPost httpPost = new HttpPost(httpUrl);// 建立httpPost return sendHttpPost(httpPost); } /** * 發送 post請求 * * @param httpUrl * 地址 * @param params * 參數(格式:key1=value1&key2=value2) */ public String sendHttpPost(String httpUrl, String params) { HttpPost httpPost = new HttpPost(httpUrl); try { StringEntity stringEntity = new StringEntity(params, "UTF-9=8"); stringEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(stringEntity); } catch (Exception e) { e.printStackTrace(); } return sendHttpPost(httpPost); } /** * 發送 post請求 * * @param httpUrl * 地址 * @param maps * 參數 */ public String sendHttpPost(String httpUrl, Map<String, String> maps) { HttpPost httpPost = new HttpPost(httpUrl); // 建立參數隊列 List<NameValuePair> nameValuePairs = new ArrayList<>(); for (String key : maps.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, maps.get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } return sendHttpPost(httpPost); } /** * 發送 post請求(帶文件) * * @param httpUrl * 地址 * @param maps * 參數 * @param fileLists * 附件 */ public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) { HttpPost httpPost = new HttpPost(httpUrl); MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); for (String key : maps.keySet()) { meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN)); } for (File file : fileLists) { FileBody fileBody = new FileBody(file); meBuilder.addPart("files", fileBody); } HttpEntity reqEntity = meBuilder.build(); httpPost.setEntity(reqEntity); return sendHttpPost(httpPost); } /** * 發送Post請求 * * @param httpPost * @return */ private String sendHttpPost(HttpPost httpPost) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立默認的httpClient實例 httpClient = HttpClients.createDefault(); httpPost.setConfig(requestConfig); // 執行請求 response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseContent; } /** * 發送 get請求 * * @param httpUrl */ public String sendHttpGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl); return sendHttpGet(httpGet); } /** * 發送 get請求Https * * @param httpUrl */ public String sendHttpsGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl); return sendHttpGet(httpGet); } /** * 發送Get請求 * * @param httpPost * @return */ public String sendHttpGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立默認的httpClient實例 httpClient = HttpClients.createDefault(); httpGet.setConfig(requestConfig); // 執行請求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseContent; } /** * 發送Get請求Https * * @param httpPost * @return */ private String sendHttpsGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立默認的httpClient實例 PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader .load(new URL(httpGet.getURI().toString())); DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build(); httpGet.setConfig(requestConfig); // 執行請求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseContent; } }
package cn.com.demo; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class HttpClientUtilTest { @Test public void testSendHttpPost1() { String responseContent = HttpClientUtil.getInstance() .sendHttpPost("http://192.168.1.83:9090/manage!login?phone=1&password=1"); System.out.println("response Content" + responseContent); } @Test public void testSendHttpPost2() { String responseContent = HttpClientUtil.getInstance().sendHttpPost("http://localhost:8089/test/send", "username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost3() { Map<String, String> maps = new HashMap<String, String>(); maps.put("username", "test01"); maps.put("password", "123456"); String responseContent = HttpClientUtil.getInstance().sendHttpPost("http://localhost:8089/test/send", maps); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost4() { Map<String, String> maps = new HashMap<String, String>(); maps.put("username", "test01"); maps.put("password", "123456"); List<File> fileLists = new ArrayList<File>(); fileLists.add(new File("D://test//httpclient//1.png")); fileLists.add(new File("D://test//httpclient//1.txt")); String responseContent = HttpClientUtil.getInstance().sendHttpPost("http://localhost:8089/test/sendpost/file", maps, fileLists); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpGet() { String responseContent = HttpClientUtil.getInstance() .sendHttpGet("http://localhost:8089/test/send?username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpsGet() { String responseContent = HttpClientUtil.getInstance().sendHttpsGet("https://www.baidu.com"); System.out.println("reponse content:" + responseContent); } }