spring集成httpclient配置的详细过程

网友投稿 1366 2023-01-01

spring集成httpclient配置的详细过程

spring集成httpclient配置的详细过程

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

-: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

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 可免费获取。

spring httpclient

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java- 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

spring与httpclient集成方式如下:

引入jar包

org.apache.httpcomponents

httpclient

4.5.2

2.编写执行get和post请求的java类

package com.wee.common.service;

import java.io.IOException;

import java-.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;

/**

* 执行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 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 params) throws IOException {

// 创建http POST请求

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(this.requestConfig);

if (params != null) {

// 设置2个post参数,一个是scope、一个是q

aodXVT List parameters = new ArrayList();

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整合配置文件

class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"

destroy-method="close">

class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"

destroy-method="close">

factory-bean="httpClientBuilder" factory-method="build" scope="prototype">

factory-bean="httpClientBuilder" factory-method="build" scope="prototype">

destroy-method="shutdown">

destroy-method="shutdown">

4.httpclient.properties

httpClient.maxTotal=200

httpClient.defaultMaxPerRoute=50

httpClient.connectTimeout=1000

httpClient.connectionRequestTimeout=500

httpClient.socketTimeout=10000

httpClient.staleConnectionCheckEnabled=true

5.使用一个单独的线程完成连接池中的无效链接的清理

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();

}

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:义乌企业app开发公司(义乌软件开发公司)
下一篇:常用小程序组件库(微信小程序 组件库)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~