package com.util;

 import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* commons-httpclient(停更)与httpclient(继续升级中)
*
* HTTP连接池请求,支持http和https请求,
* <p>
* 基于org.apache.httpcomponents.httpcore<version>4.4.10</version>
* </p>
* <p>
* 基于org.apache.httpcomponents.httpclient<version>4.5.6</version>
* </p>
*
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class HttpClientPoolUtil {
private static final String ENCODING = "UTF-8";
public static final int DEFAULT_CONNECT_TIMEOUT = 6000;
public static final int DEFAULT_READ_TIMEOUT = 6000;
public static final int DEFAULT_CONNECT_REQUEST_TIMEOUT = 6000;
private static final int MAX_TOTAL = 64;
private static final int MAX_PER_ROUTE = 32;
private static final RequestConfig requestConfig;
private static final PoolingHttpClientConnectionManager connectionManager;
private static final HttpClientBuilder httpBuilder;
private static final CloseableHttpClient httpClient;
private static final CloseableHttpClient httpsClient;
private static SSLContext sslContext; static {
try {
sslContext = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] {tm}, null);
} catch (Exception e) {
e.printStackTrace();
}
} static {
requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_READ_TIMEOUT).setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECT_REQUEST_TIMEOUT).build();
@SuppressWarnings("deprecation")
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
.build();
connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(MAX_TOTAL);
connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
httpBuilder = HttpClientBuilder.create();
httpBuilder.setDefaultRequestConfig(requestConfig);
httpBuilder.setConnectionManager(connectionManager);
httpClient = httpBuilder.build();
httpsClient = httpBuilder.build();
} /**
* GET
*
* @param url
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url)
throws Exception {
return doGet(url, false);
} /**
* GET
*
* @param url
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url, boolean https)
throws Exception {
return doGet(url, null, null, https);
} /**
* GET
*
* @param url
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url, Map<String, String> params, boolean https)
throws Exception {
return doGet(url, null, params, https);
} /**
* GET
*
* @param url
* @param headers
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params, boolean https)
throws Exception {
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建HTTP对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setConfig(requestConfig);
// 设置请求头
setHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
if (https) {
return getHttpClientResult(httpResponse, httpsClient, httpGet);
} else {
return getHttpClientResult(httpResponse, httpClient, httpGet);
}
} finally {
httpGet.releaseConnection();
release(httpResponse);
}
} /**
* POST不带参数
*
* @param url
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url)
throws Exception {
return doPost(url, Boolean.FALSE);
} /**
* @param url
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, boolean https)
throws Exception {
return doPost(url, null, (Map<String, String>)null, https);
} /**
* 带请求参数
*
* @param url
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, Map<String, String> params, boolean https)
throws Exception {
return doPost(url, null, params, https);
} /**
* POST
*
* @param url
* @param headers
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params, boolean https)
throws Exception {
// 创建HTTP对象
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置请求头
setHeader(headers, httpPost);
// 封装请求参数
setParam(params, httpPost);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
if (https) {
return getHttpClientResult(httpResponse, httpsClient, httpPost);
} else {
return getHttpClientResult(httpResponse, httpClient, httpPost);
}
} finally {
httpPost.releaseConnection();
release(httpResponse);
}
} /**
* POST请求JSON
*
* @param url
* @param headers
* @param json
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, String json, boolean https)
throws Exception {
// 创建HTTP对象
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置请求头
setHeader(headers, httpPost);
StringEntity stringEntity = new StringEntity(json, ENCODING);
stringEntity.setContentEncoding(ENCODING);
httpPost.setEntity(stringEntity);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
if (https) {
return getHttpClientResult(httpResponse, httpsClient, httpPost);
} else {
return getHttpClientResult(httpResponse, httpClient, httpPost);
}
} finally {
httpPost.releaseConnection();
release(httpResponse);
}
} /**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url)
throws Exception {
return doPut(url);
} /**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params)
throws Exception {
// CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
setParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
httpPut.releaseConnection();
release(httpResponse);
}
} /**
* 不带请求参数
*
* @param url
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doDelete(String url)
throws Exception {
// CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
httpDelete.releaseConnection();
release(httpResponse);
}
} /**
* 带请求参数
*
* @param url
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doDelete(String url, Map<String, String> params, boolean https)
throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params, https);
} /**
* 设置封装请求头
*
* @param params
* @param httpMethod
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static void setHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (MapUtils.isNotEmpty(params)) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
} /**
* 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static void setParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (MapUtils.isNotEmpty(params)) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
} /**
* 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod)
throws Exception {
// 执行请求
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} /**
* 释放资源
*
* @param httpResponse
* @throws IOException
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static void release(CloseableHttpResponse httpResponse)
throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
}
} package com.util; import java.io.Serializable; @SuppressWarnings("serial")
public class HttpClientResult implements Serializable {
/**
* 响应状态码
*/
private int code; /**
* 响应数据
*/
private String content; public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public HttpClientResult() {
super();
} public HttpClientResult(int code) {
super();
this.code = code;
} public HttpClientResult(int code, String content) {
super();
this.code = code;
this.content = content;
} @Override
public String toString() {
return "HttpClientResult [code=" + code + ", content=" + content + "]";
}
}

基于httpclient的一些常用方法封装的更多相关文章

  1. HttpClient 常用方法封装

    简介 在平时写代码中,经常需要对接口进行访问,对于 http 协议 rest 风格的接口请求,大多使用 HttpClient 工具进行编写,想着方便就寻思着把一些常用的方法进行封装,便于平时快速的使用 ...

  2. 基于表单数据的封装,泛型,反射以及使用BeanUtils进行处理

    在Java Web开发过程中,会遇到很多的表单数据的提交和对表单数据的处理.而每次都需要对这些数据的字段进行一个一个的处理就显得尤为繁琐,在Java语言中,面向对象的存在目的便是为了消除重复代码,减少 ...

  3. java Map常用方法封装

      java Map常用方法封装 CreationTime--2018年7月16日15点59分 Author:Marydon 1.准备工作 import java.util.HashMap; impo ...

  4. 基于iOS 10、realm封装的下载器

    代码地址如下:http://www.demodashi.com/demo/11653.html 概要 在决定自己封装一个下载器前,我本以为没有那么复杂,可在实际开发过程中困难重重,再加上iOS10和X ...

  5. Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)

    package com.ad.ssp.engine.common; import java.io.IOException; import java.util.ArrayList; import jav ...

  6. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

  7. 基于HttpClient实现网络爬虫~以百度新闻为例

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/40891791 基于HttpClient4.5实现网络爬虫请訪问这里:http:/ ...

  8. 基于HttpClient 4.3的可訪问自签名HTTPS网站的新版工具类

    本文出处:http://blog.csdn.net/chaijunkun/article/details/40145685,转载请注明.因为本人不定期会整理相关博文,会对相应内容作出完好.因此强烈建议 ...

  9. 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)

    近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增.删.改.查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基 ...

随机推荐

  1. Python创建一个简单的区块链

    区块链(Blockchain)是一种分布式账本(listributed ledger),它是一种仅供增加(append-only),内容不可变(immutable)的有序(ordered)链式数据结构 ...

  2. Windows系统下curl的下载和配置

    curl的下载和配置 简介:用URL规则在命令行下工作的文件传输工具. 下载:下载地址为 https://curl.haxx.se/download.html,在最底部找到Windows的版本,我下载 ...

  3. CF948B Primal Sport

    题目链接:http://codeforces.com/contest/948/problem/B 知识点: 素数 解题思路: \(f(x)\) 表示 \(x\) 的最大素因子.不难想到:\(X_1 \ ...

  4. JVM调优总结(三)-垃圾回收面临的问题

    如何区分垃圾 上面说到的“引用计数”法,通过统计控制生成对象和删除对象时的引用数来判断.垃圾回收程序收集计数为0的对象即可.但是这种方法无法解决循环引用.所以,后来实现的垃圾判断算法中,都是从程序运行 ...

  5. 小智的旅行(Bridge)51nod 提高组试题

    luogu AC传送门(官方数据) 题目描述 小智最喜欢旅行了,这次,小智来到了一个岛屿众多的地方,有N座岛屿,编号为0到N-1,岛屿之间 由一些桥连接,可以从桥的任意一端到另一端,由于岛屿可能比较大 ...

  6. eatwhatApp开发实战(四)

    之前我们做了添加店铺了功能,接下来我们做删除功能,并介绍对话框的使用方法. 在init()中注册listview的item点击监听 //注册监听 shop_lv.setOnItemClickListe ...

  7. Matlab矩阵学习三 矩阵的运算

    Matlab矩阵的运算 一.矩阵的加减 在matlab中,矩阵的加减和数的加减符号一样,都是"+"和”-“,不同的是两个进行运算的矩阵维度必须相同  二.数乘  三.乘法 矩阵乘法 ...

  8. ucoreos_lab1

    前言 最近觉得自己之前蛮多基础课学的并不咋滴,便想再补补.前段时间突然看到清华的操作系统实验,于是乎就打算试试,一边学一边做实验,然后通过博客来记录记录. 实验内容 lab1 中包含一个 bootlo ...

  9. 副业收入是我做程序媛的3倍,工作外的B面人生

    到“程序员”,多数人脑海里首先想到的大约是:为人木讷.薪水超高.工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是 ...

  10. Rocket - devices - TLDeadlock

    https://mp.weixin.qq.com/s/Zv4HE7zMBzHbsWGg3pa9fg 简单介绍TLDeadlock的实现. 1. TLDeadlock TLDeadlock是抽象类Dev ...