RestTemplate 请求 http 和https

 @Bean(name = "httpRestTemplate")
    public RestTemplate httpRestTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(20000);
        factory.setConnectTimeout(3000);
        RestTemplate restTemplate = new RestTemplate(factory);
        // 找出并修改默认的StringHttpMessageConverter
        // 关闭Accept-Charset的输出(防止输出超长的编码列表)
        // 设置默认编码为UTF-8
        boolean stringConverterFound = false;
        for (HttpMessageConverter httpMessageConverter : restTemplate.getMessageConverters()) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter)httpMessageConverter;
                stringHttpMessageConverter.setWriteAcceptCharset(false);
                stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
                stringConverterFound = true;
                break;
            }
        }
        if (!stringConverterFound) {
            // 如果不存在StringHttpMessageC onverter,则创建一个
            StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
            stringHttpMessageConverter.setWriteAcceptCharset(false);
            restTemplate.getMessageConverters().add(stringHttpMessageConverter);
        }
        return restTemplate;
    }

    /**
     * @description 初始化https客户端请求BEAN
     * @return RestTemplate请求实体类
     */
    @Bean(name = "httpsRestTemplate")
    public  RestTemplate httpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        HttpClient httpClient = HttpClientBuilder.create()
                .setSSLSocketFactory(csf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .build();


        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(httpClient);
        requestFactory.setReadTimeout(20000);
        requestFactory.setConnectTimeout(3000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
//        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());

        restTemplate.setErrorHandler(new CustomErrorHandler());


        // 找出并修改默认的StringHttpMessageConverter
        // 关闭Accept-Charset的输出(防止输出超长的编码列表)
        // 设置默认编码为UTF-8
        boolean stringConverterFound = false;
        for (HttpMessageConverter httpMessageConverter : restTemplate.getMessageConverters()) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter)httpMessageConverter;
                stringHttpMessageConverter.setWriteAcceptCharset(false);
                stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
                stringConverterFound = true;
                break;
            }
        }
        if (!stringConverterFound) {
            // 如果不存在StringHttpMessageC onverter,则创建一个
            StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
            stringHttpMessageConverter.setWriteAcceptCharset(false);
            restTemplate.getMessageConverters().add(stringHttpMessageConverter);
        }
        return restTemplate;
    }








/**
 *  restTemplate自定义响应状态
 * @author Administrator
 * @date  2020/9/2 17:55
 */
public class CustomErrorHandler implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return true;
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {

    }

}
//使用
 HttpEntity<String> requestEntity =new HttpEntity<>(j1.toJSONString(),null);
        ResponseEntity<String>responseEntity= httpsRestTemplate.exchange(hx_query, HttpMethod.POST, requestEntity, String.class);




//方法2平常的http 和https请求
package cn.witsky.rcs_backend.common.utils.http;

import cn.witsky.rcs_backend.common.utils.NullUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.math.BigDecimal;
import java.net.*;
import java.security.cert.X509Certificate;

/**
 * 通用http发送方法
 *
 * @author libo
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * post请求
     *
     * @param url            url地址
     * @param jsonParam      参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public static String httpPost(String url, String jsonParam, boolean noNeedResponse) {
        //post请求返回结果
        HttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(60000).setConnectionRequestTimeout(60000)
                .setSocketTimeout(60000).build();
        HttpPost method = new HttpPost(url);
        method.setConfig(requestConfig);
        String str = "";
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            /**请求发送成功,并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {

                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }

                } catch (Exception e) {
                    log.error("响应体异常", e);
                }
            } else {
                log.error("http请求失败,响应码为{}", result.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("请求失败", e);
        }
        return str;
    }


    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            System.out.println("**************" + result.length());
            System.out.println("**************" + result.toString().getBytes().length);
            //log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 发送HTTP_POST请求,json格式数据,提供給发送邮箱使用
     *
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static String sendPostByJson(String url, String body) throws Exception {
        HttpPost post = null;
        String resData = null;
        CloseableHttpResponse result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            post = new HttpPost(url);
            HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
            post.setHeader("Content-Type", "application/json");
            post.setEntity(entity2);
            result = httpclient.execute(post);
            if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
                resData = EntityUtils.toString(result.getEntity());
            }
        } catch (Exception e) {
            return "";
        } finally {
            if (result != null) {
                result.close();
            }
            if (post != null) {
                post.releaseConnection();
            }
        }
        return resData;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            String urlNameString = url + "?" + param;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !ret.trim().equals("")) {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }


    /**
     * 测试
     */
    public static long getSize(String urlpath) {
        // 随便一个网络图片地址
        // 得到数据
        byte[] imageFromURL = getImageFromURL(urlpath);
        // 转换
        //float byte2kb = bytes2kb(imageFromURL.length);
        if (NullUtil.isNull(imageFromURL)) {
            return 0;
        }
        return imageFromURL.length;
    }

    /**
     * 根据图片地址获取图片信息
     *
     * @param urlPath 网络图片地址
     */
    public static byte[] getImageFromURL(String urlPath) {
        // 字节数组
        byte[] data = null;
        // 输入流
        InputStream is = null;
        // Http连接对象
        HttpURLConnection conn = null;
        try {
            // Url对象
            URL url = new URL(urlPath);
            // 打开连接
            conn = (HttpURLConnection) url.openConnection();
            // 打开读取 写入是setDoOutput
//	        conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置请求方式
            conn.setRequestMethod("GET");
            // 设置超时时间
            conn.setConnectTimeout(6000);
            // 得到访问的数据流
            is = conn.getInputStream();
            // 验证访问状态是否是200 正常
            if (conn.getResponseCode() == 200) {
                data = readInputStream(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    // 关闭流
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 关闭连接
            if(!NullUtil.isNull(conn)){
                conn.disconnect();
            }
        }
        return data;
    }

    /**
     * 将流转换为字节
     *
     * @param is
     * @return
     */
    public static byte[] readInputStream(InputStream is) {
        /**
         * 捕获内存缓冲区的数据,转换成字节数组
         * ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的实例向数组中写入或读出byte型数据。
         * 在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。
         */
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 创建字节数组 1024 = 1M
        byte[] buffer = new byte[1024];
        // 防止无限循环
        int length = -1;
        try {
            // 循环写入数据到字节数组
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            // 强制刷新,扫尾工作,主要是为了,让数据流在管道的传输工程中全部传输过去,防止丢失数据
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 字节流转换字节数组
        byte[] data = baos.toByteArray();
        try {
            // 关闭读取流
            is.close();
            // 关闭写入流
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 将获取到的字节数转换为KB,MB模式
     *
     * @param bytes
     * @return
     */
    public static float bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
        if (returnValue > 1) {
            return returnValue;
        }
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
        return returnValue;
    }

}



// 第三种https 
 
   @Bean(name = "httpsTemplate")
    public HttpsTemplate httpsTemplate()  {

        return new HttpsTemplate.Builder().build();
    }



package cn.witsky.rcsapi.https;

import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
import org.apache.hc.client5.http.HttpRequestRetryStrategy;
import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeaderElementIterator;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: zgs
 * @description: https请求模板类
 * @date: 2020-04-20 14:41
 **/
public class HttpsTemplate {

    private CloseableHttpClient httpClient;

    private Charset charset;
//    private Header defaluHeader = new BasicHeader("Content-type", MediaType.APPLICATION_XML_VALUE);
    private ContentType contentType;

    private HttpsTemplate(final Builder builder) {

        this.charset = Charset.forName(builder.encoding);
//        this.contentType = ContentType.APPLICATION_XML.withCharset(charset);
        this.contentType = ContentType.create("application/xml");
        SSLContext sslcontext = null;
        try {

            TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

            sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();
//            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);

//            sslcontext = SSLContexts.custom()
//                    .loadTrustMaterial(new TrustStrategy() {
//                        @Override
//                        public boolean isTrusted(
//                                final X509Certificate[] chain,
//                                final String authType) throws CertificateException {
//                            final X509Certificate cert = chain[0];
//                            return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
//                        }
//                    })
//                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactoryBuilder.create()
                .setSslContext(sslcontext)
                .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setTlsVersions(TLS.V_1_2)
                .build();

        Registry<ConnectionSocketFactory> registry = RegistryBuilder
                .<ConnectionSocketFactory> create()
                .register("https", sslsf).build();

        // 连接管理器
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
//        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setMaxTotal(builder.maxTotalConnections);
        manager.setDefaultMaxPerRoute(builder.maxConnectionsPerRoute);

        SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)     //是否立即发送数据,设置为true会关闭Socket缓冲,默认为false
                .setSoReuseAddress(true) //是否可以在一个进程关闭Socket后,即使它还没有释放端口,其它进程还可以立即重用端口
                .setSoTimeout(Timeout.ofSeconds(builder.socketTimeout))       //接收数据的等待超时时间,单位ms
                .setSoLinger(TimeValue.ofMilliseconds(0))
                .setSoKeepAlive(true)
                .build();
        manager.setDefaultSocketConfig(socketConfig);


        // 连接保活策略
        ConnectionKeepAliveStrategy strategy = new ConnectionKeepAliveStrategy() {
            @Override
            public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {

                BasicHeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HttpHeaders.KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.next();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return  TimeValue.ofMilliseconds(Long.parseLong(value) * 1000);
                        } catch(NumberFormatException ignore) {
                        }
                    }
                }
                return  TimeValue.ofMilliseconds(builder.defaultKeepAliveTime * 1000);
            }
        };

        // 其他参数
        RequestConfig config = RequestConfig
                .custom()
                .setConnectTimeout(builder.connectionTimeout * 1000, TimeUnit.SECONDS)
                .setConnectionRequestTimeout(builder.requestTimeout * 1000,TimeUnit.SECONDS)
                .build();
        HttpRequestRetryStrategy httpRequestRetryStrategy = new HttpRequestRetryStrategy() {
            @Override
            public boolean retryRequest(HttpRequest httpRequest, IOException e, int i, HttpContext httpContext) {
                if (i < 3) {
                    return true;
                }else {
                    return false;
                }
            }

            @Override
            public boolean retryRequest(HttpResponse httpResponse, int i, HttpContext httpContext) {
                return false;
            }

            @Override
            public TimeValue getRetryInterval(HttpResponse httpResponse, int i, HttpContext httpContext) {
                return TimeValue.ofMilliseconds(2000);
            }
        };
        this.httpClient = HttpClients
                .custom()
                .setConnectionManager(manager)
                .setKeepAliveStrategy(strategy)
                .setDefaultRequestConfig(config)
                .setRetryStrategy(httpRequestRetryStrategy)
                .build();

        new Thread(new ConnectionCleaner().connectionManager(manager), "ConnectionCleaner").start();

    }




    public HttpResult exchange(String url, HttpMethod method, String reqBody, Header[] headers, Map<String,String> uriVariables) throws URISyntaxException, HttpClientException {
        //组装URI
        URIBuilder ub = new URIBuilder(url);
        ub.setCharset(charset);
        if(null != uriVariables&&uriVariables.size() > 0){
            Iterator<String> it = uriVariables.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                ub.setParameter(key, uriVariables.get(key));
            }
        }
        URI uri = ub.build();

        //不传默认为GET
        if(null == method) {
            method = HttpMethod.GET;
        }
        HttpUriRequestBase httpReq = method.create(uri);
        //设置请求体
        if (reqBody != null) {
            StringEntity entity = new StringEntity(reqBody, charset);
            httpReq.setEntity(entity);
            httpReq.setHeader("Content-Length", entity.getContentLength());
        }

        //设置HttpHeader
        if(null != headers&&headers.length > 0){
            httpReq.setHeaders(headers);
        }

        return execute(httpReq);
    }


    private HttpResult execute(HttpUriRequest request) throws HttpClientException {

        try {
            ClassicHttpResponse httpResponse = httpClient.execute(request);
            int status = httpResponse.getCode();
            String result = null;
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, charset);
                //触发归还连接到连接池
                EntityUtils.consume(entity);
            }
            Header[] header = httpResponse.getHeaders();
            return new HttpResult(status, result,header);
        } catch (Exception e) {
            throw new HttpClientException(e);
        }
    }




    public static class Builder {

        private int maxTotalConnections = 200;

        private int maxConnectionsPerRoute = 10;

        private int defaultKeepAliveTime = 60;

        private int connectionTimeout = 3;

        private int requestTimeout = 20;

        private int socketTimeout = 10;

        private String encoding = "UTF-8";

        public Builder maxTotalConnections(int maxTotalConnections) {
            this.maxTotalConnections = maxTotalConnections;
            return this;
        }

        public Builder maxConnectionsPerRoute(int maxConnectionsPerRoute) {
            this.maxConnectionsPerRoute = maxConnectionsPerRoute;
            return this;
        }

        public Builder defaultKeepAliveTime(int defaultKeepAliveTime) {
            this.defaultKeepAliveTime = defaultKeepAliveTime;
            return this;
        }

        public Builder encoding(String encoding) {
            this.encoding = encoding;
            return this;
        }

        public Builder connectionTimeout(int connectionTimeout) {
            this.connectionTimeout = connectionTimeout;
            return this;
        }

        public Builder requestTimeout(int requestTimeout) {
            this.requestTimeout = requestTimeout;
            return this;
        }

        public Builder socketTimeout(int socketTimeout) {
            this.socketTimeout = socketTimeout;
            return this;
        }

        public HttpsTemplate build() {
            return new HttpsTemplate(this);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值