zoukankan      html  css  js  c++  java
  • 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();
                }
            }
        }
    }
    

      

                       

  • 相关阅读:
    i春秋暑期训练营丨渗透测试工程师开课啦
    CTF必备技能丨Linux Pwn入门教程——环境配置
    i春秋四周年中奖名单出炉丨确认过眼神,你是中奖人
    i春秋四周年福利趴丨一纸证书教你赢在起跑线
    「你学习,我买单」i春秋四周年精品课程福利专场
    i春秋四周年庆典狂欢丨价值6000元的Web安全课程免费送啦
    倒计时3天!i春秋四周年盛典狂欢,钜惠不停
    「学习攻略」0基础转型白帽黑客第一步是什么?
    奖金高达150万元的NEST即将上线,速来报名
    「白帽挖洞技能」YxCMS 1.4.7 漏洞分析
  • 原文地址:https://www.cnblogs.com/zyzcj/p/7840866.html
Copyright © 2011-2022 走看看