httpclient pool帮助类
摘自爬虫类 用于频繁请求减少网络消耗
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ClassUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
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.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; /**
* http请求池
*/
public class HttpClientUtil {
//超时时间
static final int timeOut = 6 * 1000;
//httpclient
private static CloseableHttpClient httpClient = null;
//锁校验
private final static Object syncLock = new Object(); private static void config(HttpRequestBase httpRequestBase) {
// // 设置Header等
// httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
// httpRequestBase
// .setHeader("Accept",
// "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// httpRequestBase.setHeader("Accept-Language",
// "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");// "en-US,en;q=0.5");
// httpRequestBase.setHeader("Accept-Charset",
// "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeOut)
.setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpRequestBase.setConfig(requestConfig);
} /**
* 获取HttpClient对象
*
* @return
* @author zyz
* @create
*/
public static CloseableHttpClient getHttpClient(String url) {
String hostname = url.split("/")[2];
int port = 80;
if (hostname.contains(":")) {
String[] arr = hostname.split(":");
hostname = arr[0];
port = Integer.parseInt(arr[1]);
}
if (httpClient == null) {
synchronized (syncLock) {
if (httpClient == null) {
System.out.println("创建httpclient"+System.currentTimeMillis());
httpClient = createHttpClient(40, 40, 100, hostname, port);
}
}
}
return httpClient;
} /**
* 创建httpclient对象
* @param maxTotal 最大连接
* @param maxPerRoute 每个路由最大连接数
* @param maxRoute
* @param hostname
* @param port
* @return
*/
public static CloseableHttpClient createHttpClient(int maxTotal,
int maxPerRoute, int maxRoute, String hostname, int port) {
// ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
// .getSocketFactory();
// LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
// .getSocketFactory();
// Registry<ConnectionSocketFactory> registry = RegistryBuilder
// .<ConnectionSocketFactory> create().register("http", plainsf)
// .register("https", sslsf).build();
//长连接保持30秒
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
// 将最大连接数增加
cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute);
HttpHost httpHost = new HttpHost(hostname, port);
// 将目标主机的最大连接数增加
cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
//关闭无效链接
cm.closeExpiredConnections();
// 请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception,
int executionCount, HttpContext context) {
if (executionCount >= 5) {// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// SSL握手异常
return false;
} HttpClientContext clientContext = HttpClientContext
.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
//构建httpclient
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setRetryHandler(httpRequestRetryHandler)
//保持长连接
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).build();
return httpClient;
} /**
* 设置post请求参数
* @param httpost
* @param params 参数
*/
// private static void setPostParams(HttpPost httpost,
// Map<String, Object> params) {
// List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// NameValuePair pair1 = new BasicNameValuePair("Content_type","application/json");
// nvps.add(pair1);
// Set<String> keySet = params.keySet();
// for (String key : keySet) {
// nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
// }
// try {
// httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// }
private static void setPostParams(HttpPost httpost,Map<String, Object> params,String contentType) {
try {
HttpEntity httpEntity= new StringEntity(JSONObject.toJSONString(params),contentType,"UTF-8");
httpost.setEntity(httpEntity);
} catch (Exception e) {
}
} /**
* post 获取内容
* @param url
* @param params
* @return
* @throws Exception
*/
public static String post(String url, Map<String, Object> params) throws Exception {
HttpPost httppost = new HttpPost(url);
config(httppost);
httppost.setHeader("Content_type","application/json");
setPostParams(httppost, params,"application/json");
CloseableHttpResponse closeableHttpResponse = null;
try { closeableHttpResponse = getHttpClient(url).execute(httppost,
HttpClientContext.create());
// int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
HttpEntity entity = closeableHttpResponse.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
throw e;
} finally {
try {
if (closeableHttpResponse != null)
closeableHttpResponse.close();
httppost.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* get 请求url 获取数据
* @param url
* @return
*/
public static String get(String url) {
HttpGet httpget = new HttpGet(url);
config(httpget);
CloseableHttpResponse response = null;
try {
response = getHttpClient(url).execute(httpget,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
httpget.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} public static void main(String[] args) throws Exception{
Map<String,Object> map = new HashMap<String,Object>();
map.put("__query_select_id","fam.CarpayMapper10.33.selectCarPayNotBalancedDetail");
map.put("d1","2017-12-01 23:59:59");
map.put("d2","2017-12-02 23:59:59");
map.put("page",1);
map.put("pageSize",20);
String url ="http://bug-dus.kxtx.cn/kxtx-dus/dus/controller/queryjson";
// // URL列表数组
// for (int i = 0; i <1000 ; i++) {
// String string =post("http://bug-dus.kxtx.cn/kxtx-dus/dus/controller/queryjson",map);
// System.out.println(string);
// } long start = System.currentTimeMillis();
try {
ExecutorService executors = Executors.newFixedThreadPool(1000);
CountDownLatch countDownLatch = new CountDownLatch(1000);
for (int i = 0; i <1000 ; i++) {
executors.execute(new GetRunnable(url,countDownLatch,map));
}
countDownLatch.await();
executors.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("线程" + Thread.currentThread().getName() + ","
+ System.currentTimeMillis() + ", 所有线程已完成,开始进入下一步!");
} long end = System.currentTimeMillis();
System.out.println("consume -> " + (end - start));
} static class GetRunnable implements Runnable {
private CountDownLatch countDownLatch;
private String url;
private Map<String,Object> map; public GetRunnable(String url, CountDownLatch countDownLatch,Map<String,Object> map) {
this.url = url;
this.countDownLatch = countDownLatch;
this.map = map;
} public void run() {
try {
String result = HttpClientUtil.post(url,map);
JSONObject obj = JSONObject.parseObject(result);
String data = obj.getString("data");
System.out.println("result="+result);
System.out.println("data="+data);
}catch (Exception e){ }finally {
countDownLatch.countDown();
}
}
}
}
httpclient pool帮助类的更多相关文章
- android6.0SDK 删除HttpClient的相关类的解决方法
本文转载自博客:http://blog.csdn.net/yangqingqo/article/details/48214865 android6.0SDK中删除HttpClient的相关类的解决方法 ...
- 通过Thread Pool Executor类解析线程池执行任务的核心流程
摘要:ThreadPoolExecutor是Java线程池中最核心的类之一,它能够保证线程池按照正常的业务逻辑执行任务,并通过原子方式更新线程池每个阶段的状态. 本文分享自华为云社区<[高并发] ...
- 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...
- android 6.0 SDK中删除HttpClient的相关类的解决方法
一.出现的情况 在eclipse或 android studio开发, 设置android SDK的编译版本为23时,且使用了httpClient相关类的库项目:如android-async-http ...
- HttpClient的帮助类
/// <summary> /// http请求类 /// </summary> public class HttpHelper { private HttpClient _h ...
- HttpClient封装工具类
import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; ...
- HttpClient 通信工具类
package com.taotao.web.service; import java.util.ArrayList; import java.util.List; import java.util. ...
- webrequest、httpwebrequest、webclient、HttpClient 四个类的区别
一.在 framework 开发环境下: webrequest.httpwebreques 都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...
- HttpClient请求工具类
package com.yangche.utils; import org.apache.http.NameValuePair; import org.apache.http.client.Clien ...
随机推荐
- android平台蓝牙编程
Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样利用android平台提供的蓝牙API去实现蓝牙设备之间的通信,蓝牙设备之间的通信主要包括了四个步骤:设置蓝牙设 ...
- Arrays.copyof(···)与System.arraycopy(···)区别
首先观察先System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)的声明: public stati ...
- 矩阵快速幂——POJ3070
矩阵快速幂和普通的快速幂差不多,只不过写起来比较麻烦一点,需要重载*运算符. 模板: struct mat { int m[maxn][maxn]; }unit; mat operator * (ma ...
- IOS-网络(发送JSON数据给服务器和多值参数)
三步走: 1.使用POST请求 2.设置请求头 [request setValue:@"application/json" forHTTPHeaderField:@"Co ...
- 5G RRC——为NAS层提供连接管理,消息传递等服务; 对接入网的底层协议实体提供参数配置的功能; 负责UE移动性管理相关的测量、控制等功能
from:http://www.cnblogs.com/kkdd-2013/p/3868676.html 1 RRC协议功能 为NAS层提供连接管理,消息传递等服务: 对接入网的底层协议实体提供参数配 ...
- LINUX创建管道文件
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- springboot---数据整合篇
本文讲解 Spring Boot 基础下,如何使用 JDBC,配置数据源和通过 JdbcTemplate 编写数据访问. 环境依赖 修改 POM 文件,添加spring-boot-starter-jd ...
- Sql 基础问题
Ref Projection and Selection 联结查询的原理(笛卡尔积) 设计 MySQL 数据表的时候一般都有一列为自增 ID,这样设计原因是什么,有什么好处?
- opencv之批量转换灰度图并保存
当图片名字有数字规律时,批量处理方式. ①srcImage 图片名字有规律 ②将srcImage文件下的图片,转换为灰度图并保存入grayImage文件夹. ③ #include <iostre ...
- BZOJ4025: 二分图【线段树分治】【带撤销的并查集】
Description 神犇有一个n个节点的图.因为神犇是神犇,所以在T时间内一些边会出现后消失.神犇要求出每一时间段内这个图是否是二分图.这么简单的问题神犇当然会做了,于是他想考考你. Input ...