摘自爬虫类  用于频繁请求减少网络消耗

  1. import java.io.IOException;
  2. import java.io.InterruptedIOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.net.UnknownHostException;
  5. import java.util.*;
  6. import java.util.concurrent.CountDownLatch;
  7. import java.util.concurrent.ExecutorService;
  8. import java.util.concurrent.Executors;
  9. import java.util.concurrent.TimeUnit;
  10.  
  11. import javax.net.ssl.SSLException;
  12. import javax.net.ssl.SSLHandshakeException;
  13.  
  14. import com.alibaba.fastjson.JSONObject;
  15. import org.apache.commons.lang3.ClassUtils;
  16. import org.apache.http.HttpEntity;
  17. import org.apache.http.HttpEntityEnclosingRequest;
  18. import org.apache.http.HttpHost;
  19. import org.apache.http.HttpRequest;
  20. import org.apache.http.NameValuePair;
  21. import org.apache.http.NoHttpResponseException;
  22. import org.apache.http.client.HttpRequestRetryHandler;
  23. import org.apache.http.client.config.RequestConfig;
  24. import org.apache.http.client.entity.UrlEncodedFormEntity;
  25. import org.apache.http.client.methods.CloseableHttpResponse;
  26. import org.apache.http.client.methods.HttpGet;
  27. import org.apache.http.client.methods.HttpPost;
  28. import org.apache.http.client.methods.HttpRequestBase;
  29. import org.apache.http.client.protocol.HttpClientContext;
  30. import org.apache.http.conn.ConnectTimeoutException;
  31. import org.apache.http.conn.routing.HttpRoute;
  32. import org.apache.http.entity.StringEntity;
  33. import org.apache.http.impl.client.CloseableHttpClient;
  34. import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
  35. import org.apache.http.impl.client.HttpClients;
  36. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  37. import org.apache.http.protocol.HttpContext;
  38. import org.apache.http.util.EntityUtils;
  39.  
  40. /**
  41. * http请求池
  42. */
  43. public class HttpClientUtil {
  44. //超时时间
  45. static final int timeOut = 6 * 1000;
  46. //httpclient
  47. private static CloseableHttpClient httpClient = null;
  48. //锁校验
  49. private final static Object syncLock = new Object();
  50.  
  51. private static void config(HttpRequestBase httpRequestBase) {
  52. // // 设置Header等
  53. // httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
  54. // httpRequestBase
  55. // .setHeader("Accept",
  56. // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  57. // httpRequestBase.setHeader("Accept-Language",
  58. // "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");// "en-US,en;q=0.5");
  59. // httpRequestBase.setHeader("Accept-Charset",
  60. // "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
  61. // 配置请求的超时设置
  62. RequestConfig requestConfig = RequestConfig.custom()
  63. .setConnectionRequestTimeout(timeOut)
  64. .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
  65. httpRequestBase.setConfig(requestConfig);
  66. }
  67.  
  68. /**
  69. * 获取HttpClient对象
  70. *
  71. * @return
  72. * @author zyz
  73. * @create
  74. */
  75. public static CloseableHttpClient getHttpClient(String url) {
  76. String hostname = url.split("/")[2];
  77. int port = 80;
  78. if (hostname.contains(":")) {
  79. String[] arr = hostname.split(":");
  80. hostname = arr[0];
  81. port = Integer.parseInt(arr[1]);
  82. }
  83. if (httpClient == null) {
  84. synchronized (syncLock) {
  85. if (httpClient == null) {
  86. System.out.println("创建httpclient"+System.currentTimeMillis());
  87. httpClient = createHttpClient(40, 40, 100, hostname, port);
  88. }
  89. }
  90. }
  91. return httpClient;
  92. }
  93.  
  94. /**
  95. * 创建httpclient对象
  96. * @param maxTotal 最大连接
  97. * @param maxPerRoute 每个路由最大连接数
  98. * @param maxRoute
  99. * @param hostname
  100. * @param port
  101. * @return
  102. */
  103. public static CloseableHttpClient createHttpClient(int maxTotal,
  104. int maxPerRoute, int maxRoute, String hostname, int port) {
  105. // ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
  106. // .getSocketFactory();
  107. // LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
  108. // .getSocketFactory();
  109. // Registry<ConnectionSocketFactory> registry = RegistryBuilder
  110. // .<ConnectionSocketFactory> create().register("http", plainsf)
  111. // .register("https", sslsf).build();
  112. //长连接保持30秒
  113. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
  114. // 将最大连接数增加
  115. cm.setMaxTotal(maxTotal);
  116. // 将每个路由基础的连接增加
  117. cm.setDefaultMaxPerRoute(maxPerRoute);
  118. HttpHost httpHost = new HttpHost(hostname, port);
  119. // 将目标主机的最大连接数增加
  120. cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
  121. //关闭无效链接
  122. cm.closeExpiredConnections();
  123. // 请求重试处理
  124. HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
  125. public boolean retryRequest(IOException exception,
  126. int executionCount, HttpContext context) {
  127. if (executionCount >= 5) {// 如果已经重试了5次,就放弃
  128. return false;
  129. }
  130. if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
  131. return true;
  132. }
  133. if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
  134. return false;
  135. }
  136. if (exception instanceof InterruptedIOException) {// 超时
  137. return false;
  138. }
  139. if (exception instanceof UnknownHostException) {// 目标服务器不可达
  140. return false;
  141. }
  142. if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
  143. return false;
  144. }
  145. if (exception instanceof SSLException) {// SSL握手异常
  146. return false;
  147. }
  148.  
  149. HttpClientContext clientContext = HttpClientContext
  150. .adapt(context);
  151. HttpRequest request = clientContext.getRequest();
  152. // 如果请求是幂等的,就再次尝试
  153. if (!(request instanceof HttpEntityEnclosingRequest)) {
  154. return true;
  155. }
  156. return false;
  157. }
  158. };
  159. //构建httpclient
  160. CloseableHttpClient httpClient = HttpClients.custom()
  161. .setConnectionManager(cm)
  162. .setRetryHandler(httpRequestRetryHandler)
  163. //保持长连接
  164. .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).build();
  165. return httpClient;
  166. }
  167.  
  168. /**
  169. * 设置post请求参数
  170. * @param httpost
  171. * @param params 参数
  172. */
  173. // private static void setPostParams(HttpPost httpost,
  174. // Map<String, Object> params) {
  175. // List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  176. // NameValuePair pair1 = new BasicNameValuePair("Content_type","application/json");
  177. // nvps.add(pair1);
  178. // Set<String> keySet = params.keySet();
  179. // for (String key : keySet) {
  180. // nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
  181. // }
  182. // try {
  183. // httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  184. // } catch (UnsupportedEncodingException e) {
  185. // e.printStackTrace();
  186. // }
  187. // }
  188. private static void setPostParams(HttpPost httpost,Map<String, Object> params,String contentType) {
  189. try {
  190. HttpEntity httpEntity= new StringEntity(JSONObject.toJSONString(params),contentType,"UTF-8");
  191. httpost.setEntity(httpEntity);
  192. } catch (Exception e) {
  193. }
  194. }
  195.  
  196. /**
  197. * post 获取内容
  198. * @param url
  199. * @param params
  200. * @return
  201. * @throws Exception
  202. */
  203. public static String post(String url, Map<String, Object> params) throws Exception {
  204. HttpPost httppost = new HttpPost(url);
  205. config(httppost);
  206. httppost.setHeader("Content_type","application/json");
  207. setPostParams(httppost, params,"application/json");
  208. CloseableHttpResponse closeableHttpResponse = null;
  209. try {
  210.  
  211. closeableHttpResponse = getHttpClient(url).execute(httppost,
  212. HttpClientContext.create());
  213. // int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
  214. HttpEntity entity = closeableHttpResponse.getEntity();
  215. String result = EntityUtils.toString(entity, "utf-8");
  216. EntityUtils.consume(entity);
  217. return result;
  218. } catch (Exception e) {
  219. throw e;
  220. } finally {
  221. try {
  222. if (closeableHttpResponse != null)
  223. closeableHttpResponse.close();
  224. httppost.releaseConnection();
  225. } catch (IOException e) {
  226. e.printStackTrace();
  227. }
  228. }
  229. }
  230.  
  231. /**
  232. * get 请求url 获取数据
  233. * @param url
  234. * @return
  235. */
  236. public static String get(String url) {
  237. HttpGet httpget = new HttpGet(url);
  238. config(httpget);
  239. CloseableHttpResponse response = null;
  240. try {
  241. response = getHttpClient(url).execute(httpget,
  242. HttpClientContext.create());
  243. HttpEntity entity = response.getEntity();
  244. String result = EntityUtils.toString(entity, "utf-8");
  245. EntityUtils.consume(entity);
  246. return result;
  247. } catch (IOException e) {
  248. e.printStackTrace();
  249. } finally {
  250. try {
  251. if (response != null)
  252. response.close();
  253. httpget.releaseConnection();
  254. } catch (IOException e) {
  255. e.printStackTrace();
  256. }
  257. }
  258. return null;
  259. }
  260.  
  261. public static void main(String[] args) throws Exception{
  262. Map<String,Object> map = new HashMap<String,Object>();
  263. map.put("__query_select_id","fam.CarpayMapper10.33.selectCarPayNotBalancedDetail");
  264. map.put("d1","2017-12-01 23:59:59");
  265. map.put("d2","2017-12-02 23:59:59");
  266. map.put("page",1);
  267. map.put("pageSize",20);
  268. String url ="http://bug-dus.kxtx.cn/kxtx-dus/dus/controller/queryjson";
  269. // // URL列表数组
  270. // for (int i = 0; i <1000 ; i++) {
  271. // String string =post("http://bug-dus.kxtx.cn/kxtx-dus/dus/controller/queryjson",map);
  272. // System.out.println(string);
  273. // }
  274.  
  275. long start = System.currentTimeMillis();
  276. try {
  277. ExecutorService executors = Executors.newFixedThreadPool(1000);
  278. CountDownLatch countDownLatch = new CountDownLatch(1000);
  279. for (int i = 0; i <1000 ; i++) {
  280. executors.execute(new GetRunnable(url,countDownLatch,map));
  281. }
  282. countDownLatch.await();
  283. executors.shutdown();
  284. } catch (InterruptedException e) {
  285. e.printStackTrace();
  286. } finally {
  287. System.out.println("线程" + Thread.currentThread().getName() + ","
  288. + System.currentTimeMillis() + ", 所有线程已完成,开始进入下一步!");
  289. }
  290.  
  291. long end = System.currentTimeMillis();
  292. System.out.println("consume -> " + (end - start));
  293. }
  294.  
  295. static class GetRunnable implements Runnable {
  296. private CountDownLatch countDownLatch;
  297. private String url;
  298. private Map<String,Object> map;
  299.  
  300. public GetRunnable(String url, CountDownLatch countDownLatch,Map<String,Object> map) {
  301. this.url = url;
  302. this.countDownLatch = countDownLatch;
  303. this.map = map;
  304. }
  305.  
  306. public void run() {
  307. try {
  308. String result = HttpClientUtil.post(url,map);
  309. JSONObject obj = JSONObject.parseObject(result);
  310. String data = obj.getString("data");
  311. System.out.println("result="+result);
  312. System.out.println("data="+data);
  313. }catch (Exception e){
  314.  
  315. }finally {
  316. countDownLatch.countDown();
  317. }
  318. }
  319. }
  320. }

  

httpclient pool帮助类的更多相关文章

  1. android6.0SDK 删除HttpClient的相关类的解决方法

    本文转载自博客:http://blog.csdn.net/yangqingqo/article/details/48214865 android6.0SDK中删除HttpClient的相关类的解决方法 ...

  2. 通过Thread Pool Executor类解析线程池执行任务的核心流程

    摘要:ThreadPoolExecutor是Java线程池中最核心的类之一,它能够保证线程池按照正常的业务逻辑执行任务,并通过原子方式更新线程池每个阶段的状态. 本文分享自华为云社区<[高并发] ...

  3. 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类

    推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...

  4. android 6.0 SDK中删除HttpClient的相关类的解决方法

    一.出现的情况 在eclipse或 android studio开发, 设置android SDK的编译版本为23时,且使用了httpClient相关类的库项目:如android-async-http ...

  5. HttpClient的帮助类

    /// <summary> /// http请求类 /// </summary> public class HttpHelper { private HttpClient _h ...

  6. HttpClient封装工具类

    import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; ...

  7. HttpClient 通信工具类

    package com.taotao.web.service; import java.util.ArrayList; import java.util.List; import java.util. ...

  8. webrequest、httpwebrequest、webclient、HttpClient 四个类的区别

    一.在 framework 开发环境下: webrequest.httpwebreques  都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...

  9. HttpClient请求工具类

    package com.yangche.utils; import org.apache.http.NameValuePair; import org.apache.http.client.Clien ...

随机推荐

  1. XML_CPP_资料_libXml2_01

    ZC: 看了一些 C/C++的XML文章,也看了一些 Qt的 QXmlQuery/QXmlSimpleReader/QXmlStreamReader/QXmlStreamWriter 的文章.总体感觉 ...

  2. Mac Hadoop2.6(CDH5.9.2)伪分布式集群安装

    操作系统: MAC OS X 一.准备 1. JDK 1.8 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-dow ...

  3. 51nod1347思维

    1347 旋转字符串 基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题  收藏  关注 S[0...n-1]是一个长度为n的字符串,定义旋转函数Left(S)=S[1… ...

  4. 先对结果集排序然后做update、delete操作

    --先排序然后删除第n条数据delete from scott.emp where empno in (select empno                   from (select *    ...

  5. qt Cannot connect creator comm socket /tmp/qt_temp.S26613/stub-socket: No such

    Tool->Options->Environment->General 将terminal改为 xterm -e

  6. Linux jdk环境配置模板

    export JAVA_HOME=/opt/JAVA/jdk1.8.0_191export JRE_HOME=${JAVA_HOME}/jreexport CLASSPATH=.:${JAVA_HOM ...

  7. 免费获取 Kaspersky Small Office Security 90 天授权

    Kaspersky Small Office Security 是卡巴斯基出品的企业版杀毒软件,目前美国官网上官方有赠送活动,能够免费获取 90 天的授权,但必须要使用美国代理. 获取地址:http: ...

  8. New Concept English Two 10 25

    $课文23 新居 219. I had a letter from my sister yesterday. 昨天我收到了姐姐的一封信, 220. She lives in Nigeria. 她住在尼 ...

  9. angularjs指令中的require赋值含义

    前缀 寻找路劲 没有找到控制器是否抛错? 例如 Link函数中第四个参数 (no prefix) 当前指令的DOM 抛错 tabset 找到的Controller对象 ? 当前指令的DOM 不抛错 ? ...

  10. django2 显示图片 输出图片

    使用笨办法,指向图片的路径,然后输出图片. 首先路由设置: # 查看图片 path('tu/', ShowTuView.as_view(), name='image') 视图代码: import os ...