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 ...
随机推荐
- 【整理】STL中的bitset(二进制华丽解决假五维偏序题)
------------更多Bitset的运用,请看这里http://www.cnblogs.com/hua-dong/p/8519739.html. 由于在学cdq分治,看到了这道题.先来看一道题目 ...
- UVA-1612 Guess (贪心)
题目大意:考试共有三道题,n个人,每个人对每道题的可能得分已知,现在已知考后排名情况,问排名合不合理. 题目分析:贪心.贪心策略:每处理一个排名,都让他的得分尽量高. # include<ios ...
- 3321 Apple Tree 树状数组
LIANJIE:http://poj.org/problem?id=3321 给你一个多叉树,每个叉和叶子节点有一颗苹果.然后给你两个操作,一个是给你C清除某节点上的苹果或者添加(此节点上有苹果则清除 ...
- iOS UI-静态单元格与动态单元格
- 线程的同步之Synchronized在单例模式中的应用
synchronized在单例模式中的使用 在单例模式中有一种懒汉式的单例,就是类初始化的时候不创建对象.等第一次获取的时候再创建对象.这种单例在单线程下是没有问题的获取的也都是同一个对象.但是如果放 ...
- zTree简单使用
zTree使用 zTree github地址 zTree API文档 zTree插件依赖JQ所以使用zTree首先引入JQ,另外zTree的点击功能,编辑功能都是单独的文件,如需使用也要引入(也可以引 ...
- 《转》深入理解Activity启动流程(四)–Activity Task的调度算法
本文原创作者:Cloud Chou. 出处:本文链接 本系列博客将详细阐述Activity的启动流程,这些博客基于Cm 10.1源码研究. 深入理解Activity启动流程(一)--Activity启 ...
- Alpha阶段第1周/共2周 Scrum立会报告+燃尽图 03
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2248 一.小组介绍 组长:刘莹莹 组员:朱珅莹 孙韦男 祝玮琦 王玉潘 ...
- 【linux】查看进程
查询所有:ps aux 查询某个用户:ps -u abc 终止某个进程:kill
- Linux:提示符PS1个性设置
提示符PS1个性设置 1)默认PS1 echo $PS1 2)个性PS1 #去掉了默认显示的[]号#\e[1;34m\]\u:user名高亮显示并显示颜色#\e[5;33m\]\h:hostname主 ...