1 Star 2 Fork 0

孙明/HttpClientUtils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
HttpClientUtils.java 6.29 KB
一键复制 编辑 原始数据 按行查看 历史
孙明 提交于 2018-07-26 12:39 . Upload HttpClientUtils.java
package com.ipet.http.utils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
//设置连接超时时间
private static final Integer CONNECTION_TIMEOUT = 2 * 1000; //设置请求超时2秒钟 根据业务调整
private static final Integer SO_TIMEOUT = 2 * 1000; //设置等待数据超时时间2秒钟 根据业务调整
//定义了当从ClientConnectionManager中检索ManagedClientConnection实例时使用的毫秒级的超时时间
//这个参数期望得到一个java.lang.Long类型的值。如果这个参数没有被设置,默认等于CONNECTION_TIMEOUT,因此一定要设置。
private static final Integer CONN_MANAGER_TIMEOUT = 2 * 1000; //在httpclient4.2.3中我记得它被改成了一个对象导致直接用long会报错,后来又改回来了
private static PoolingHttpClientConnectionManager connMgr;
public static PoolingHttpClientConnectionManager getConnMgr() {
return connMgr;
}
private static CloseableHttpClient httpClient;
static{
//配置一个PoolingHttpClientConnectionManager
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
connMgr.setMaxTotal(500);
//例如默认每路由最高50并发,具体依据业务来定
connMgr.setDefaultMaxPerRoute(50);
httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectionRequestTimeout(CONN_MANAGER_TIMEOUT);
configBuilder.setConnectTimeout(CONNECTION_TIMEOUT);
configBuilder.setSocketTimeout(SO_TIMEOUT);
}
public enum HttpClientNewBuilder {
INSTANCE;
public CloseableHttpClient create() {
return httpClient;
}
}
public static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
public static String doGet(String url, Map<String, String> param) {
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (ParseException | URISyntaxException | IOException e) {
e.printStackTrace();
}
return resultString;
}
public static String doGet(String url) throws ClientProtocolException, URISyntaxException, IOException {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static void main(String[] args) {
HttpClientUtils.IdleConnectionMonitorThread t = new HttpClientUtils.IdleConnectionMonitorThread(connMgr);
t.start();
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
doGet("http://www.qq.com");
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/superbigjj/HttpClientUtils.git
git@gitee.com:superbigjj/HttpClientUtils.git
superbigjj
HttpClientUtils
HttpClientUtils
master

搜索帮助