轉載:https://my.oschina.net/wcyong/blog/636404
HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 java 應用程序需要直接通過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,但是對于大部分應用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,并且它支持 HTTP 協議最新的版本和建議。
sPRing與httpclient集成方式如下:
引入jar包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version></dependency>2.編寫執行get和post請求的java類
package com.wee.common.service;import java.io.IOException;import java.net.URISyntaxException;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;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.client.utils.URIBuilder;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.wee.common.bean.HttpResult;@Servicepublic class HttpClientService { @Autowired private CloseableHttpClient httpClient; @Autowired private RequestConfig requestConfig; /** * 執行GET請求 * * @param url * @return * @throws IOException * @throws ClientProtocolException */ public String doGet(String url) throws ClientProtocolException, IOException { // 創建http GET請求 HttpGet httpGet = new HttpGet(url); httpGet.setConfig(this.requestConfig); CloseableHttpResponse response = null; try { // 執行請求 response = httpClient.execute(httpGet); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { return EntityUtils.toString(response.getEntity(), "UTF-8"); } } finally { if (response != null) { response.close(); } } return null; } /** * 帶有參數的GET請求 * * @param url * @param params * @return * @throws URISyntaxException * @throws IOException * @throws ClientProtocolException */ public String doGet(String url, Map<String, String> params) throws ClientProtocolException, IOException, URISyntaxException { URIBuilder uriBuilder = new URIBuilder(url); for (String key : params.keySet()) { uriBuilder.addParameter(key, params.get(key)); } return this.doGet(uriBuilder.build().toString()); } /** * 執行POST請求 * * @param url * @param params * @return * @throws IOException */ public HttpResult doPost(String url, Map<String, String> params) throws IOException { // 創建http POST請求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(this.requestConfig); if (params != null) { // 設置2個post參數,一個是scope、一個是q List<NameValuePair> parameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { parameters.add(new BasicNameValuePair(key, params.get(key))); } // 構造一個form表單式的實體 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8"); // 將請求實體設置到httpPost對象中 httpPost.setEntity(formEntity); } CloseableHttpResponse response = null; try { // 執行請求 response = httpClient.execute(httpPost); return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); } finally { if (response != null) { response.close(); } } } /** * 執行POST請求 * * @param url * @return * @throws IOException */ public HttpResult doPost(String url) throws IOException { return this.doPost(url, null); } /** * 提交json數據 * * @param url * @param json * @return * @throws ClientProtocolException * @throws IOException */ public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException { // 創建http POST請求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(this.requestConfig); if (json != null) { // 構造一個form表單式的實體 StringEntity stringEntity = new StringEntity(json, ContentType.application_JSON); // 將請求實體設置到httpPost對象中 httpPost.setEntity(stringEntity); } CloseableHttpResponse response = null; try { // 執行請求 response = this.httpClient.execute(httpPost); return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); } finally { if (response != null) { response.close(); } } }}
HttpResult.java
public class HttpResult { /** * 狀態碼 */ private Integer status; /** * 返回數據 */ private String data; public HttpResult() { } public HttpResult(Integer status, String data) { this.status = status; this.data = data; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getData() { return data; } public void setData(String data) { this.data = data; }}
3.spring和httpClient整合配置文件
<!-- 定義連接管理器 --> <bean id="httpClientConnectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" destroy-method="close"> <!-- 最大連接數 --> <property name="maxTotal" value="${http.maxTotal}" /> <!-- 設置每個主機地址的并發數 --> <property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" /> </bean> <!-- httpclient對象構建器 --> <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder"> <!-- 設置連接管理器 --> <property name="connectionManager" ref="httpClientConnectionManager" /> </bean> <!-- 定義Httpclient對象 --> <bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient" factory-bean="httpClientBuilder" factory-method="build" scope="prototype"> </bean> <!-- 定義清理無效連接 --> <bean class="com.taotao.common.httpclient.IdleConnectionEvictor" destroy-method="shutdown"> <constructor-arg index="0" ref="httpClientConnectionManager" /> </bean> <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder"> <!-- 創建連接的最長時間 --> <property name="connectTimeout" value="${http.connectTimeout}"/> <!-- 從連接池中獲取到連接的最長時間 --> <property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}"/> <!-- 數據傳輸的最長時間 --> <property name="socketTimeout" value="${http.socketTimeout}"/> <!-- 提交請求前測試連接是否可用 --> <property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}"/> </bean> <!-- 定義請求參數 --> <bean id="requestConfig" class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder" factory-method="build"> </bean>4.httpclient.properties
httpClient.maxTotal=200httpClient.defaultMaxPerRoute=50httpClient.connectTimeout=1000httpClient.connectionRequestTimeout=500httpClient.socketTimeout=10000httpClient.staleConnectionCheckEnabled=true5.使用一個單獨的線程完成連接池中的無效鏈接的清理
package com.wee.common.httpclient;import org.apache.http.conn.HttpClientConnectionManager;public class IdleConnectionEvictor extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionEvictor(HttpClientConnectionManager connMgr) { this.connMgr = connMgr; // 啟動當前線程 this.start(); } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // 關閉失效的連接 connMgr.closeExpiredConnections(); } } } catch (InterruptedException ex) { // 結束 } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } }}新聞熱點
疑難解答