基于httpclient的一些常用方法封装
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的一些常用方法封装的更多相关文章
- HttpClient 常用方法封装
简介 在平时写代码中,经常需要对接口进行访问,对于 http 协议 rest 风格的接口请求,大多使用 HttpClient 工具进行编写,想着方便就寻思着把一些常用的方法进行封装,便于平时快速的使用 ...
- 基于表单数据的封装,泛型,反射以及使用BeanUtils进行处理
在Java Web开发过程中,会遇到很多的表单数据的提交和对表单数据的处理.而每次都需要对这些数据的字段进行一个一个的处理就显得尤为繁琐,在Java语言中,面向对象的存在目的便是为了消除重复代码,减少 ...
- java Map常用方法封装
java Map常用方法封装 CreationTime--2018年7月16日15点59分 Author:Marydon 1.准备工作 import java.util.HashMap; impo ...
- 基于iOS 10、realm封装的下载器
代码地址如下:http://www.demodashi.com/demo/11653.html 概要 在决定自己封装一个下载器前,我本以为没有那么复杂,可在实际开发过程中困难重重,再加上iOS10和X ...
- Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)
package com.ad.ssp.engine.common; import java.io.IOException; import java.util.ArrayList; import jav ...
- 适用于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通用)>,现在重新整理一 ...
- 基于HttpClient实现网络爬虫~以百度新闻为例
转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/40891791 基于HttpClient4.5实现网络爬虫请訪问这里:http:/ ...
- 基于HttpClient 4.3的可訪问自签名HTTPS网站的新版工具类
本文出处:http://blog.csdn.net/chaijunkun/article/details/40145685,转载请注明.因为本人不定期会整理相关博文,会对相应内容作出完好.因此强烈建议 ...
- 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)
近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增.删.改.查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基 ...
随机推荐
- shell脚本定时执行|关闭jar文件
编写shell脚本,用于启动.关闭jar程序: #!/bin/bash #description: 启动重启server服务 #需要配置环境变量后才能直接使用java这些变量 export JAVA_ ...
- Gym101630C Connections
题目大意: 给出一个\(n\)个点\(m\)条边的有向图,无自环无重边.要求把这个图进行删边,直到只剩下\(2n\)条边,使得图中每个点都可以相互连通. 知识点: DFS 解题思路: 从点\(1\)出 ...
- .Net基础之1——学前入门
1..Net平台 2.C#编程语言 3..Net都能做什么 Winform桌面应用程序.Internet应用程序——ASP.Net(京东.淘宝.携程网)(主推). WP8手机开发.Unity 3D游戏 ...
- 手机短号(hdu2081)
这里字符串的输入用gets_s()函数. #include<stdio.h> using namespace std; int main() { int N; scanf_s(" ...
- Higher-Order Functions Fundamentals
Higher-Order Functions A function that accepts and/or returns another function is called a higher-or ...
- JAVA局部变量和成员变量的区别
成员变量与局部变量的区别 1.在类中的位置不同 成员变量:在类中方法外面 局部变量:在方法或者代码块中,或者方法的声明上(即在参数列表中) 2.在内存中的位置不同 成员变量:在堆中(方法区中的静态区) ...
- Codeblocks运行按钮变灰,卡程序编译
实际上,当我们点击绿色运行按钮运行之后,.exe文件会开始运行,当我们点击红色调试按钮之后,会开始调试. 因此当我们在运行卡住之后,点击红色调试按钮,实际上并没有真正的结束程序,只是将窗口隐藏起来,我 ...
- PHP目录操作函数汇总
一.判断普通文件和目录 1.is_file()//判断给定文件名是否为一个正常的文件 2.is_dir()//判断给定文件名是否是一个目录二.文件的属性 1.file_exists( ...
- Ubuntu虚拟机的安装
1.在VMware中新建虚拟机 注意W10的现在强制升级VMware所以大家,安装低版本的时候提示,升级就区官网下载一个新版本的即可. 这边大家填写自己的就好,要记住自己填写的! 这边我们等一会即可. ...
- Python数据分析:pandas玩转Excel (一)
目录 1 pandas简介 2 导入 3 使用 4 读取.写入 1 pandas简介 1.Pandas是什么? Pandas是一个强大的分析结构化数据的工具集: 它的使用基础是Numpy(提供高性能的 ...