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 ...
随机推荐
- XML_CPP_资料_libXml2_01
ZC: 看了一些 C/C++的XML文章,也看了一些 Qt的 QXmlQuery/QXmlSimpleReader/QXmlStreamReader/QXmlStreamWriter 的文章.总体感觉 ...
- Mac Hadoop2.6(CDH5.9.2)伪分布式集群安装
操作系统: MAC OS X 一.准备 1. JDK 1.8 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-dow ...
- 51nod1347思维
1347 旋转字符串 基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题 收藏 关注 S[0...n-1]是一个长度为n的字符串,定义旋转函数Left(S)=S[1… ...
- 先对结果集排序然后做update、delete操作
--先排序然后删除第n条数据delete from scott.emp where empno in (select empno from (select * ...
- qt Cannot connect creator comm socket /tmp/qt_temp.S26613/stub-socket: No such
Tool->Options->Environment->General 将terminal改为 xterm -e
- Linux jdk环境配置模板
export JAVA_HOME=/opt/JAVA/jdk1.8.0_191export JRE_HOME=${JAVA_HOME}/jreexport CLASSPATH=.:${JAVA_HOM ...
- 免费获取 Kaspersky Small Office Security 90 天授权
Kaspersky Small Office Security 是卡巴斯基出品的企业版杀毒软件,目前美国官网上官方有赠送活动,能够免费获取 90 天的授权,但必须要使用美国代理. 获取地址:http: ...
- New Concept English Two 10 25
$课文23 新居 219. I had a letter from my sister yesterday. 昨天我收到了姐姐的一封信, 220. She lives in Nigeria. 她住在尼 ...
- angularjs指令中的require赋值含义
前缀 寻找路劲 没有找到控制器是否抛错? 例如 Link函数中第四个参数 (no prefix) 当前指令的DOM 抛错 tabset 找到的Controller对象 ? 当前指令的DOM 不抛错 ? ...
- django2 显示图片 输出图片
使用笨办法,指向图片的路径,然后输出图片. 首先路由设置: # 查看图片 path('tu/', ShowTuView.as_view(), name='image') 视图代码: import os ...