spring集成httpclient配置的詳細(xì)過(guò)程
一、簡(jiǎn)介
HttpClient是Apache Jakarta Common下的子項(xiàng)目,用來(lái)提供高效的、最新的、功能豐富的支持HTTP協(xié)議的客戶端編程工具包,并且它支持HTTP協(xié)議最新的版本和建議。HttpClient已經(jīng)應(yīng)用在很多的項(xiàng)目中,比如Apache Jakarta上很著名的另外兩個(gè)開(kāi)源項(xiàng)目Cactus和HTMLUnit都使用了HttpClient。
下載地址: http://hc.apache.org/downloads.cgi
二、特性
1. 基于標(biāo)準(zhǔn)、純凈的java語(yǔ)言。實(shí)現(xiàn)了Http1.0和Http1.1
2. 以可擴(kuò)展的面向?qū)ο蟮慕Y(jié)構(gòu)實(shí)現(xiàn)了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支持HTTPS協(xié)議。
4. 通過(guò)Http代理建立透明的連接。
5. 利用CONNECT方法通過(guò)Http代理建立隧道的https連接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos認(rèn)證方案。
7. 插件式的自定義認(rèn)證方案。
8. 便攜可靠的套接字工廠使它更容易的使用第三方解決方案。
9. 連接管理器支持多線程應(yīng)用。支持設(shè)置最大連接數(shù),同時(shí)支持設(shè)置每個(gè)主機(jī)的最大連接數(shù),發(fā)現(xiàn)并關(guān)閉過(guò)期的連接。
10. 自動(dòng)處理Set-Cookie中的Cookie。
11. 插件式的自定義Cookie策略。
12. Request的輸出流可以避免流中內(nèi)容直接緩沖到socket服務(wù)器。
13. Response的輸入流可以有效的從socket服務(wù)器直接讀取相應(yīng)內(nèi)容。
14. 在http1.0和http1.1中利用KeepAlive保持持久連接。
15. 直接獲取服務(wù)器發(fā)送的response code和 headers。
16. 設(shè)置連接超時(shí)的能力。
17. 實(shí)驗(yàn)性的支持http1.1 response caching。
18. 源代碼基于Apache License 可免費(fèi)獲取。
spring httpclient
HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來(lái)越多的 Java 應(yīng)用程序需要直接通過(guò) HTTP 協(xié)議來(lái)訪問(wèn)網(wǎng)絡(luò)資源。雖然在 JDK 的 java.net 包中已經(jīng)提供了訪問(wèn) HTTP 協(xié)議的基本功能,但是對(duì)于大部分應(yīng)用程序來(lái)說(shuō),JDK 庫(kù)本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
spring與httpclient集成方式如下:
引入jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2.編寫(xiě)執(zhí)行g(shù)et和post請(qǐng)求的java類(lèi)
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;
@Service
public class HttpClientService {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig requestConfig;
/**
* 執(zhí)行GET請(qǐng)求
*
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public String doGet(String url) throws ClientProtocolException, IOException {
// 創(chuàng)建http GET請(qǐng)求
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(this.requestConfig);
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpGet);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 帶有參數(shù)的GET請(qǐng)求
*
* @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());
}
/**
* 執(zhí)行POST請(qǐng)求
*
* @param url
* @param params
* @return
* @throws IOException
*/
public HttpResult doPost(String url, Map<String, String> params) throws IOException {
// 創(chuàng)建http POST請(qǐng)求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(this.requestConfig);
if (params != null) {
// 設(shè)置2個(gè)post參數(shù),一個(gè)是scope、一個(gè)是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 構(gòu)造一個(gè)form表單式的實(shí)體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
// 將請(qǐng)求實(shí)體設(shè)置到httpPost對(duì)象中
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} finally {
if (response != null) {
response.close();
}
}
}
/**
* 執(zhí)行POST請(qǐng)求
*
* @param url
* @return
* @throws IOException
*/
public HttpResult doPost(String url) throws IOException {
return this.doPost(url, null);
}
/**
* 提交json數(shù)據(jù)
*
* @param url
* @param json
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {
// 創(chuàng)建http POST請(qǐng)求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(this.requestConfig);
if (json != null) {
// 構(gòu)造一個(gè)form表單式的實(shí)體
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
// 將請(qǐng)求實(shí)體設(shè)置到httpPost對(duì)象中
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
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 {
/**
* 狀態(tài)碼
*/
private Integer status;
/**
* 返回?cái)?shù)據(jù)
*/
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">
<!-- 最大連接數(shù) -->
<property name="maxTotal" value="${http.maxTotal}" />
<!-- 設(shè)置每個(gè)主機(jī)地址的并發(fā)數(shù) -->
<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
</bean>
<!-- httpclient對(duì)象構(gòu)建器 -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<!-- 設(shè)置連接管理器 -->
<property name="connectionManager" ref="httpClientConnectionManager" />
</bean>
<!-- 定義Httpclient對(duì)象 -->
<bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
</bean>
<!-- 定義清理無(wú)效連接 -->
<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">
<!-- 創(chuàng)建連接的最長(zhǎng)時(shí)間 -->
<property name="connectTimeout" value="${http.connectTimeout}"/>
<!-- 從連接池中獲取到連接的最長(zhǎng)時(shí)間 -->
<property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}"/>
<!-- 數(shù)據(jù)傳輸?shù)淖铋L(zhǎng)時(shí)間 -->
<property name="socketTimeout" value="${http.socketTimeout}"/>
<!-- 提交請(qǐng)求前測(cè)試連接是否可用 -->
<property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}"/>
</bean>
<!-- 定義請(qǐng)求參數(shù) -->
<bean id="requestConfig" class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder" factory-method="build">
</bean>
4.httpclient.properties
httpClient.maxTotal=200 httpClient.defaultMaxPerRoute=50 httpClient.connectTimeout=1000 httpClient.connectionRequestTimeout=500 httpClient.socketTimeout=10000 httpClient.staleConnectionCheckEnabled=true
5.使用一個(gè)單獨(dú)的線程完成連接池中的無(wú)效鏈接的清理
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;
// 啟動(dòng)當(dāng)前線程
this.start();
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 關(guān)閉失效的連接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 結(jié)束
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
到此這篇關(guān)于spring集成httpclient配置的文章就介紹到這了,更多相關(guān)spring httpclient配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯?wèn)題
- Spring+Http請(qǐng)求+HttpClient實(shí)現(xiàn)傳參
- springboot整合httpClient代碼實(shí)例
- spring boot openfeign從此和httpClient說(shuō)再見(jiàn)詳析
- Spring中@Scheduled和HttpClient的連環(huán)坑
- spring boot封裝HttpClient的示例代碼
相關(guān)文章
使用JPA中@Query 注解實(shí)現(xiàn)update 操作方法(必看)
下面小編就為大家?guī)?lái)一篇使用JPA中@Query 注解實(shí)現(xiàn)update 操作方法(必看)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
SpringBoot與Quartz集成實(shí)現(xiàn)分布式定時(shí)任務(wù)集群的代碼實(shí)例
今天小編就為大家分享一篇關(guān)于SpringBoot與Quartz集成實(shí)現(xiàn)分布式定時(shí)任務(wù)集群的代碼實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03
實(shí)戰(zhàn)分布式醫(yī)療掛號(hào)系統(tǒng)登錄接口整合阿里云短信詳情
這篇文章主要為大家介紹了實(shí)戰(zhàn)分布式醫(yī)療掛號(hào)系統(tǒng)登錄接口整合阿里云短信詳情,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪<BR>2022-04-04
一天時(shí)間用Java寫(xiě)了個(gè)飛機(jī)大戰(zhàn)游戲,朋友直呼高手
前兩天我發(fā)現(xiàn)論壇有兩篇飛機(jī)大戰(zhàn)的文章異常火爆,但都是python寫(xiě)的,竟然不是我大Java,說(shuō)實(shí)話作為老java選手,我心里是有那么一些失落的,今天特地整理了這篇文章,需要的朋友可以參考下2021-05-05
關(guān)于logback日志級(jí)別動(dòng)態(tài)切換的四種方式
這篇文章主要介紹了關(guān)于logback日志級(jí)別動(dòng)態(tài)切換的四種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
JSP request.setAttribute()詳解及實(shí)例
這篇文章主要介紹了 javascript request.setAttribute()詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-02-02

