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.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
spring与httpclient集成方式如下:
引入jar包

org.apache.httpcomponentshttpclient4.5.2

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 {@Autowiredprivate CloseableHttpClient httpClient; @Autowiredprivate 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); // 判断返回状态是否为200if (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、一个是qList 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.javapublic class HttpResult {/*** 状态码*/private Integer status; /*** 返回数据*/private String data; public HttpResult() {}public HttpResult(Integer status, String data) {this.status = status; this.data = https://www.it610.com/article/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整合配置文件

4.httpclient.properties
httpClient.maxTotal=200httpClient.defaultMaxPerRoute=50httpClient.connectTimeout=1000httpClient.connectionRequestTimeout=500httpClient.socketTimeout=10000httpClient.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(); }@Overridepublic void run() {try {while (!shutdown) {synchronized (this) {wait(5000); // 关闭失效的连接connMgr.closeExpiredConnections(); }}} catch (InterruptedException ex) {// 结束}}public void shutdown() {shutdown = true; synchronized (this) {notifyAll(); }}}

【spring集成httpclient配置的详细过程】到此这篇关于spring集成httpclient配置的文章就介绍到这了,更多相关spring httpclient配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读