1. 程式人生 > >HTTP連接池

HTTP連接池

set true params eth conn cut oge ava 請求

     <context:property-placeholder location="classpath:conf/framework/httpclient.properties"/>
	<!-- 定義連接管理器 -->
	<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.avcon.platform.dledc.res.service.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>

  

@Service
public 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();
			}
		}
	}

  

HTTP連接池