httpclient

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
        </dependency>
    public static String HttpPost(String url, String jsonString) {
        
        /**
         * 测出超时重试机制为了防止超时不生效而设置
         *  如果直接放回false,不重试
         *  这里会根据情况进行判断是否重试
         */
        HttpRequestRetryHandler retry = new HttpRequestRetryHandler() {
            
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {// 如果已经重试了3次,就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return true;
                }
                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;
            }
        };
        
        
        
        //https://blog.csdn.net/c364902709/article/details/80427585      socket属性设置说明
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(2000).build();
        
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); 
        // 设置最大连接数
        connManager.setMaxTotal(200);
        // 设置每个连接的路由数
        connManager.setDefaultMaxPerRoute(20);
        connManager.setDefaultSocketConfig(socketConfig);
        
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000)
                .setConnectionRequestTimeout(2000).build();
        
        // 创建CloseableHttpClient
        //CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
        CloseableHttpClient httpClient = HttpClients.custom()
        // 把请求相关的超时信息设置到连接客户端
        .setDefaultRequestConfig(requestConfig)
        // 把请求重试设置到连接客户端
        .setRetryHandler(retry)
        // 配置连接池管理对象
        .setConnectionManager(connManager)
        //设置连接池最大连接数
        .setMaxConnTotal(10)
        .build();
        
        
        
        
        HttpPost httpPost = new HttpPost(url);// 实现HttpPost
        httpPost.setConfig(requestConfig); // 设置httpPost的状态参数
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");// 设置httpPost的请求头中的MIME类型为json
        httpPost.setHeader("Accept", "application/json");
        
        StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
        httpPost.setEntity(requestEntity);// 设置请求体
        
        CloseableHttpResponse response = null;
        
        try {
            response = httpClient.execute(httpPost, new BasicHttpContext());// 执行请求返回结果
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                return resultStr;
            } else {
                return null;
            }
        } catch (Exception e) {
            // logger.error("httpPost method exception handle-- > " + e);
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();// 最后关闭response
                } catch (IOException e) {
                    // logger.error("httpPost method IOException handle -- > " + e);
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    // logger.error("httpPost method exception handle-- > " + e);
                }
            }
        }
    }
    public static String HttpGet(String url) {
        // 单位毫秒
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();// 设置请求的状态参数

        CloseableHttpClient httpclient = HttpClients.createDefault();// 创建 CloseableHttpClient
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);// 返回请求执行结果
            int statusCode = response.getStatusLine().getStatusCode();// 获取返回的状态值
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            } else {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                return result;
            }
        } catch (Exception e) {
            // logger.error("httpget Exception handle-- > " + e);
        } finally {
            if (response != null) {
                try {
                    response.close();// 关闭response
                } catch (IOException e) {
                    // logger.error("httpget IOException handle-- > " + e);
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();// 关闭httpclient
                } catch (IOException e) {
                    // logger.error("httpget IOException handle-- > " + e);
                }
            }
        }
        return null;
    }

 

posted on 2019-07-10 09:31  code前行 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/codefeng/p/11161828.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值