介绍
- HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
- HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
案例
@Test
public void test01() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = "https://www.baidu.com";
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200){
System.out.println("请求有效");
}
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
}
Spring整合HttpClient
编辑propertis属性配置文件
#从连接池中获取到连接的最长时间
http.request.connectionRequestTimeout=500
#5000
http.request.connectTimeout=5000
#数据传输的最长时间
http.request.socketTimeout=30000
#提交请求前测试连接是否可用
http.request.staleConnectionCheckEnabled=true
#设置连接总数
http.pool.maxTotal=200
#设置每个地址的并发数
http.pool.defaultMaxPerRoute=100
编辑springIOC配置文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/property/httpclient.properties</value>
</list>
</property>
</bean>
编辑HttpClient配置文件
<bean class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" id="httpClientConnectionManager"
destroy-method="close">
<property name="maxTotal" value="${http.pool.maxTotal}"/>
<property name="defaultMaxPerRoute" value="${http.pool.defaultMaxPerRoute}"/>
</bean>
<bean class="org.apache.http.impl.client.HttpClientBuilder" id="httpClientBuilder" factory-method="create">
<property name="connectionManager" ref="httpClientConnectionManager"/>
</bean>
<bean factory-bean="httpClientBuilder" factory-method="build"/>
<bean class="com.jt.common.util.IdleConnectionEvictor" destroy-method="shutdown">
<constructor-arg index="0" ref="httpClientConnectionManager"/>
<constructor-arg index="1" value="60000"/>
</bean>
<bean class="org.apache.http.client.config.RequestConfig.Builder" id="requestConfigBuilder">
<property name="connectionRequestTimeout" value="${http.request.connectionRequestTimeout}"/>
<property name="connectTimeout" value="${http.request.connectTimeout}"/>
<property name="socketTimeout" value="${http.request.socketTimeout}"/>
<property name="staleConnectionCheckEnabled" value="${http.request.staleConnectionCheckEnabled}"/>
</bean>
<bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build"/>
编辑工具类
@Service
public class HttpClientService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
@Autowired(required=false)
private CloseableHttpClient httpClient;
@Autowired(required=false)
private RequestConfig requestConfig;
public String doGet(String url,Map<String, String> params,String encode) throws Exception {
LOGGER.info("执行GET请求,URL = {}", url);
if(null != params){
URIBuilder builder = new URIBuilder(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.setParameter(entry.getKey(), entry.getValue());
}
url = builder.build().toString();
}
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
if(encode == null){
encode = "UTF-8";
}
return EntityUtils.toString(response.getEntity(), encode);
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
public String doGet(String url, String encode) throws Exception{
return this.doGet(url, null, encode);
}
public String doGet(String url) throws Exception{
return this.doGet(url, null, null);
}
public String doGet(String url, Map<String, String> params) throws Exception {
return this.doGet(url, params, null);
}
public String doPost(String url, Map<String, String> params,String encode) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if (null != params) {
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for (Map.Entry<String, String> entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity formEntity = null;
if(encode!=null){
formEntity = new UrlEncodedFormEntity(parameters,encode);
}else{
formEntity = new UrlEncodedFormEntity(parameters);
}
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
public String doPost(String url, Map<String, String> params) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if (null != params) {
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for (Map.Entry<String, String> entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
public String doPostJson(String url, String json) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if(null != json){
StringEntity stringEntity = new StringEntity(json,"UTF-8");
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
}