• 高性能高可用的全能httpclient方法封装


    废话不多说,直接干代码

    一、http请求配置

    /**
     * HttpClientConfig http请求配置
     */
    public class HttpClientConfig {
    
        /**
         * 连接时间 ms
         */
        protected int CONNECT_TIMING_OUT = 300000;
        /**
         * 请求响应时间 ms
         */
        protected int RESPONSE_TIMING_OUT = 300000;
    
        /**
         * 发起请求时间 ms
         */
        protected int REQUEST_TIMING_OUT = 300000;
    
        public HttpClientConfig(int CONNECT_TIMING_OUT, int RESPONSE_TIMING_OUT, int REQUEST_TIMING_OUT) {
            this.CONNECT_TIMING_OUT = CONNECT_TIMING_OUT;
            this.RESPONSE_TIMING_OUT = RESPONSE_TIMING_OUT;
            this.REQUEST_TIMING_OUT = REQUEST_TIMING_OUT;
        }
    
        public HttpClientConfig(){
    
        }
    
        public static HttpClientConfig defaultConfig(){
            return new HttpClientConfig();
        }
    
        public int getCONNECT_TIMING_OUT() {
            return CONNECT_TIMING_OUT;
        }
    
        public void setCONNECT_TIMING_OUT(int CONNECT_TIMING_OUT) {
            this.CONNECT_TIMING_OUT = CONNECT_TIMING_OUT;
        }
    
        public int getRESPONSE_TIMING_OUT() {
            return RESPONSE_TIMING_OUT;
        }
    
        public void setRESPONSE_TIMING_OUT(int RESPONSE_TIMING_OUT) {
            this.RESPONSE_TIMING_OUT = RESPONSE_TIMING_OUT;
        }
    
        public int getREQUEST_TIMING_OUT() {
            return REQUEST_TIMING_OUT;
        }
    
        public void setREQUEST_TIMING_OUT(int REQUEST_TIMING_OUT) {
            this.REQUEST_TIMING_OUT = REQUEST_TIMING_OUT;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    二、主体代码

    package com.xxx.xxx.bsmiddleware.httpclient;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpHost;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    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.HttpPut;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.BasicHttpEntity;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.CollectionUtils;
    import org.springframework.util.ObjectUtils;
    
    import javax.net.ssl.*;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.zip.GZIPInputStream;
    import java.util.zip.GZIPOutputStream;
    
    public class HttpClientUtil {
    
        private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
        private static final String DEFAULT_CHARSET_UTF8 = "UTF-8";
        private static final String DEFAULT_CONTENT_TYPE_JSON = "application/json";
    
        /**
         * @param url    请求路径
         * @param params 请求参数
         * @return
         * @throws Exception
         */
        public static String get(String url, Map<String, Object> params, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                if (params != null) {
                    StringBuilder sb = new StringBuilder();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                    }
                    if (sb.length() > 0) {
                        if (url.indexOf("?") > -1) {
                            url = url + sb.toString();
                        } else {
                            sb.delete(0, 1);
                            url = url + "?" + sb.toString();
                        }
                    }
                }
                HttpGet httpGet = new HttpGet(url);
    //            httpGet.addHeader("Content-Type", "application/json");
    //            httpGet.addHeader("User-Agent", name);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                return EntityUtils.toString(httpEntity, "UTF-8");
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
    
        /**
         * @param url    请求路径
         * @param params 请求参数
         * @return
         * @throws Exception
         */
        public static InputStream getFile(InputStream inputStream,String url, Map<String, Object> params, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                if (params != null) {
                    StringBuilder sb = new StringBuilder();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                    }
                    if (sb.length() > 0) {
                        if (url.indexOf("?") > -1) {
                            url = url + sb.toString();
                        } else {
                            sb.delete(0, 1);
                            url = url + "?" + sb.toString();
                        }
                    }
                }
                HttpGet httpGet = new HttpGet(url);
    //            httpGet.addHeader("Content-Type", "application/json");
    //            httpGet.addHeader("User-Agent", name);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                inputStream = httpResponse.getEntity().getContent();
    //            return EntityUtils.toString(httpEntity, "UTF-8")
                return inputStream;
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
    //            if (httpClient != null) {
    //                try {
                        httpClient.close();
    //                } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
    //                }
    //            }
            }
        }
    
        /**
         * @param url    请求路径
         * @param params 请求参数
         * @return
         * @throws Exception
         */
        public static String getForHeader(String url, Map<String, Object> params, Map<String, String> headerParam, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                if (params != null) {
                    StringBuilder sb = new StringBuilder();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                    }
                    if (sb.length() > 0) {
                        if (url.indexOf("?") > -1) {
                            url = url + sb.toString();
                        } else {
                            sb.delete(0, 1);
                            url = url + "?" + sb.toString();
                        }
                    }
                }
                HttpGet httpGet = new HttpGet(url);
                //header参数
                if (headerParam != null && headerParam.size() > 0) {
                    for (String key : headerParam.keySet()) {
                        httpGet.addHeader(key, headerParam.get(key));
                    }
                }
    //            httpGet.addHeader("Content-Type", "application/json");
    //            httpGet.addHeader("User-Agent", name);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                return EntityUtils.toString(httpEntity, "UTF-8");
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
    
        /**
         * @param url    请求路径
         * @param params 请求参数
         * @return
         */
        public static String post(String url, Map<String, Object> params, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPost httpPost = new HttpPost(url);
                if (params != null && params.size() > 0) {
                    List<NameValuePair> pairs = new ArrayList<>();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        NameValuePair pair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                        pairs.add(pair);
                    }
                    HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                    httpPost.setEntity(httpEntity);
                }
                HttpResponse httpResponse = httpClient.execute(httpPost);
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    HttpEntity httpEntity = httpResponse.getEntity();
                    return EntityUtils.toString(httpEntity, "UTF-8");
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + httpResponse.getEntity().toString());
                }
            } catch (Exception e) {
                throw e;
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
        /**
         * 参数JSON格式 Post
         *
         * @param url 请求路径
         * @return
         */
        public static String jsonPost(String url, Object paramVO, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            String result = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPost httpPost = new HttpPost(url);
    //            System.out.println("请求参数:"+JSON.toJSONString(paramVO));
    //            LOGGER.info("请求参数:"+ JSON.toJSONString(paramVO));
                StringEntity requestEntity = new StringEntity(JSON.toJSONString(paramVO), "UTF-8");
                requestEntity.setContentType("application/json");
                httpPost.setEntity(requestEntity);
    
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity, "UTF-8");
                EntityUtils.consume(httpEntity);
    
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    return result;
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + result);
                }
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
        /**
         * 参数JSON格式 Post,带header的
         *
         * @param url 请求路径
         * @return
         */
        public static String jsonPostHeader(String url, Object paramVO,Map<String, String> headerParam, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            String result = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPost httpPost = new HttpPost(url);
                //header参数
                if (headerParam != null && headerParam.size() > 0) {
                    for (String key : headerParam.keySet()) {
                        httpPost.addHeader(key, headerParam.get(key));
                    }
                }
    //            LOGGER.info("请求参数:"+ JSON.toJSONString(paramVO));
                StringEntity requestEntity = new StringEntity(JSON.toJSONString(paramVO), "UTF-8");
                requestEntity.setContentType("application/json");
                httpPost.setEntity(requestEntity);
    
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity, "UTF-8");
                EntityUtils.consume(httpEntity);
    
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    return result;
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + result);
                }
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
        /**
         * @param url    请求路径
         * @param params 请求参数
         * @return
         */
        public static String put(String url, Map<String, Object> params, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPut httpPut = new HttpPut(url);
                if (params != null && params.size() > 0) {
                    List<NameValuePair> pairs = new ArrayList<>();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        NameValuePair pair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                        pairs.add(pair);
                    }
                    HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                    httpPut.setEntity(httpEntity);
                }
                HttpResponse httpResponse = httpClient.execute(httpPut);
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    HttpEntity httpEntity = httpResponse.getEntity();
                    return EntityUtils.toString(httpEntity, "UTF-8");
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode());
                }
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
    
        /**
         * put带请求头
         * @return
         */
        public static String putForHeader(String url, Object paramVO, Map<String, String> headerParam, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPut httpPut = new HttpPut(url);
                //header参数
                if (headerParam != null && headerParam.size() > 0) {
                    LOGGER.info("put请求Header:" + JSON.toJSONString(headerParam));
                    for (String key : headerParam.keySet()) {
                        httpPut.addHeader(key, headerParam.get(key));
                    }
                }
                LOGGER.info("请求参数:"+ JSON.toJSONString(paramVO));
                StringEntity requestEntity = new StringEntity(JSON.toJSONString(paramVO), "UTF-8");
                requestEntity.setContentType("application/json");
                httpPut.setEntity(requestEntity);
                HttpResponse httpResponse = httpClient.execute(httpPut);
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    HttpEntity httpEntity = httpResponse.getEntity();
                    return EntityUtils.toString(httpEntity, "UTF-8");
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode());
                }
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
    
        /**
         * 发送带head的请求
         *
         * @param url
         * @param headerParam
         * @param bodyParam
         * @param contentType
         * @param charSet
         * @return
         * @throws Exception
         */
        public static String post(String url, Map<String, String> headerParam, Map<Object, Object> bodyParam, String contentType, String charSet, HttpClientConfig... configList) throws Exception {
            String content_type = contentType;
            if (content_type == null || "".equals(content_type)) content_type = DEFAULT_CONTENT_TYPE_JSON;
    
            String char_set = charSet;
            if (char_set == null || "".equals(char_set)) char_set = DEFAULT_CHARSET_UTF8;
    
            HttpPost httpPost = new HttpPost(url);
    
            //header参数
            if (headerParam != null && headerParam.size() > 0) {
                LOGGER.info("Post请求Header:" + JSON.toJSONString(headerParam));
                for (String key : headerParam.keySet()) {
                    httpPost.addHeader(key, headerParam.get(key));
                }
            }
    
            //entity数据
            if (bodyParam != null) {
                //x-www-form-urlencoded类型
                if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
                    if (bodyParam instanceof Map) {
    
                        @SuppressWarnings("unchecked")
                        Map<Object, Object> params = bodyParam;
                        if (!CollectionUtils.isEmpty(params)) {
                            List<NameValuePair> pairs = new ArrayList<>();
                            for (Map.Entry<Object, Object> entry : params.entrySet()) {
                                NameValuePair pair = new BasicNameValuePair(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
                                pairs.add(pair);
                            }
                            HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                            httpPost.setEntity(httpEntity);
                            LOGGER.info("post请求body:" + httpEntity.toString());
                        }
                    }
                } else {//json或其他类型
                    LOGGER.info("Post请求Body:" + JSON.toJSONString(bodyParam));
                    StringEntity entity = new StringEntity(JSON.toJSONString(bodyParam), char_set);
                    entity.setContentEncoding(char_set);
                    entity.setContentType(content_type);
    
                    httpPost.setEntity(entity);
                }
            }
    
            String resultStr = "";
            CloseableHttpResponse response = null;
            try {
                response = createClient(url, getHttpConfig(configList)).execute(httpPost);
                resultStr = EntityUtils.toString(response.getEntity(), char_set);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                    httpPost.releaseConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            LOGGER.info("Post请求返回:" + resultStr);
            return resultStr;
        }
    
        /**
         * 发送Gzip压缩请求
         *
         * @param sendurl
         * @param bytes
         * @param headMap
         * @return
         * @throws Exception
         */
        public static byte[] postGzip(String sendurl, byte[] bytes, Map<String, String> headMap, HttpClientConfig... configList) throws Exception {
            HttpClientConfig httpClientConfig = getHttpConfig(configList);
            HttpURLConnection con = null;
            ByteArrayOutputStream baos = null;
            GZIPInputStream reader = null;
            GZIPOutputStream zip = null;
            try {
                con = getConnection(sendurl);
                if (headMap != null) {
                    for (Map.Entry<String, String> en : headMap.entrySet()) {
                        con.setRequestProperty(en.getKey(), en.getValue());
                    }
                }
                con.setConnectTimeout(httpClientConfig.CONNECT_TIMING_OUT);
                con.setReadTimeout(httpClientConfig.RESPONSE_TIMING_OUT);
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setAllowUserInteraction(true);
                con.setUseCaches(false);
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-type", "application/gzip");
                zip = new GZIPOutputStream(con.getOutputStream());
                zip.write(bytes);
                zip.flush();
                zip.close();
                reader = new GZIPInputStream(con.getInputStream());
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int len = -1;
                while ((len = reader.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                con.disconnect();
                baos.close();
                return baos.toByteArray();
            } catch (Exception e) {
                LOGGER.error("GzipPost:{}, 出现异常,error: {}", sendurl, e.getMessage());
                throw new RuntimeException("请求异常:" + e.getMessage());
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (zip != null) {
                    zip.close();
                }
                if (baos != null) {
                    baos.close();
                }
                if (con != null) {
                    con.disconnect();
                }
            }
        }
    
        public static String post2(String url, Map<String, Object> params,String contentType ,HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPost httpPost = new HttpPost(url);
                if (params != null && params.size() > 0) {
                    List<NameValuePair> pairs = new ArrayList<>();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        NameValuePair pair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                        pairs.add(pair);
                    }
                    HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
    //                requestEntity.setContentType("application/json");
                    httpPost.setEntity(httpEntity);
                }
                HttpResponse httpResponse = httpClient.execute(httpPost);
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    HttpEntity httpEntity = httpResponse.getEntity();
                    return EntityUtils.toString(httpEntity, "UTF-8");
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + httpResponse.getEntity().toString());
                }
            } catch (Exception e) {
                throw e;
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
    
        /**
         * 参数对象 格式 Post,带header的
         *
         * @param url 请求路径
         * @return
         */
        public static String postHeader(String url, JSONArray paramVO, Map<String, String> headerParam, HttpClientConfig... configList) throws Exception {
            CloseableHttpClient httpClient = null;
            String result = null;
            try {
                httpClient = createClient(url, getHttpConfig(configList));
                HttpPost httpPost = new HttpPost(url);
                //header参数
                if (headerParam != null && headerParam.size() > 0) {
                    for (String key : headerParam.keySet()) {
                        httpPost.addHeader(key, headerParam.get(key));
                    }
                }
                LOGGER.info("请求参数:"+ JSON.toJSONString(paramVO));
                StringEntity requestEntity = new StringEntity(JSON.toJSONString(paramVO), "UTF-8");
                requestEntity.setContentType("application/json");
                httpPost.setEntity(requestEntity);
    
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity, "UTF-8");
                EntityUtils.consume(httpEntity);
    
                if (httpResponse.getStatusLine().getStatusCode() < 400) {
                    return result;
                } else {
                    throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + result);
                }
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        throw new Exception(e.getMessage(), e);
                    }
                }
            }
        }
    
        private static CloseableHttpClient createHttpsClient(HttpClientConfig config) throws Exception {
            X509TrustManager xtm = new X509TrustManager() {
    
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }
    
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    
                }
    
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
            };
            SSLContext ctx = SSLContext.getInstance("SSL");
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new HostnameVerifier() {
    
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
    
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(config.CONNECT_TIMING_OUT)
                    .setConnectionRequestTimeout(config.REQUEST_TIMING_OUT)
    //                .setProxy(new HttpHost("172.16.25.140", 9999))
                    .setSocketTimeout(config.RESPONSE_TIMING_OUT).build();
            CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).build();
            return httpClient;
        }
    
        private static CloseableHttpClient createHttpClient(HttpClientConfig config) {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(config.CONNECT_TIMING_OUT)
                    .setConnectionRequestTimeout(config.REQUEST_TIMING_OUT)
                    .setSocketTimeout(config.RESPONSE_TIMING_OUT).build();
    
            CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
            return httpClient;
        }
    
        private static CloseableHttpClient createClient(String url, HttpClientConfig config) throws Exception {
            if (url.startsWith("https")) {    //https请求
                return createHttpsClient(config);
            } else {    //http请求
                return createHttpClient(config);
            }
        }
    
        private static HttpURLConnection getConnection(String reqUrl) throws Exception {
            if (reqUrl.startsWith("https")) {
                return getHttpsConnection(reqUrl);
            } else {
                return getHttpConnection(reqUrl);
            }
        }
    
        private static HttpURLConnection getHttpsConnection(String reqUrl) throws IOException, KeyManagementException, NoSuchAlgorithmException {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL url = new URL(reqUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            return conn;
        }
    
        private static HttpURLConnection getHttpConnection(String reqUrl) throws IOException {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            return conn;
        }
    
        private static class TrustAnyTrustManager implements X509TrustManager {
    
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
    
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
    
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }
        }
    
        private static class TrustAnyHostnameVerifier implements HostnameVerifier {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }
    
        private static HttpClientConfig getHttpConfig(HttpClientConfig[] configList) {
            if (ObjectUtils.isEmpty(configList)) {
                return HttpClientConfig.defaultConfig();
            }
            return configList[0];
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554
    • 555
    • 556
    • 557
    • 558
    • 559
    • 560
    • 561
    • 562
    • 563
    • 564
    • 565
    • 566
    • 567
    • 568
    • 569
    • 570
    • 571
    • 572
    • 573
    • 574
    • 575
    • 576
    • 577
    • 578
    • 579
    • 580
    • 581
    • 582
    • 583
    • 584
    • 585
    • 586
    • 587
    • 588
    • 589
    • 590
    • 591
    • 592
    • 593
    • 594
    • 595
    • 596
    • 597
    • 598
    • 599
    • 600
    • 601
    • 602
    • 603
    • 604
    • 605
    • 606
    • 607
    • 608
    • 609
    • 610
    • 611
    • 612
    • 613
    • 614
    • 615
    • 616
    • 617
    • 618
    • 619
    • 620
    • 621
    • 622
    • 623
    • 624
    • 625
    • 626
    • 627
    • 628
    • 629
    • 630
    • 631
    • 632
    • 633
    • 634
    • 635
    • 636
    • 637
    • 638
    • 639
    • 640
    • 641
    • 642
    • 643
    • 644
    • 645
    • 646
    • 647
    • 648
    • 649
    • 650
    • 651
    • 652
    • 653
    • 654
    • 655
    • 656
    • 657
    • 658
    • 659
    • 660
    • 661
    • 662
    • 663
    • 664
    • 665
    • 666
    • 667
    • 668
    • 669
    • 670
    • 671
    • 672
    • 673
    • 674
    • 675
    • 676
    • 677
    • 678
    • 679
    • 680
    • 681
    • 682
    • 683
    • 684
    • 685
    • 686
    • 687
    • 688
    • 689
    • 690
    • 691
    • 692
    • 693
    • 694
    • 695
    • 696
    • 697
    • 698
    • 699
    • 700
    • 701
    • 702
    • 703
    • 704
    • 705
    • 706
    • 707
    • 708
    • 709
    • 710
    • 711
    • 712
    • 713
    • 714
    • 715
    • 716
    • 717
    • 718
    • 719
    • 720
    • 721
    • 722

    三、应用例子

               try {
                    inputStream = HttpClientUtil.getFile(inputStream,url, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    return  "通过url获取标准简历文件流失败,url:" + url;
                }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    或者

            String res = null;
            try {
                res = HttpClientUtil.jsonPost(Url + "/xxx/xxxxxxx" + "?access_token=" + token,params);
            } catch (Exception e) {
                e.printStackTrace();
                return "人员状态异常:" + e.getMessage();
            }
            JSONObject jsonObject = JSON.parseObject(res);
            String code = jsonObject.getString("code");
            if ("200".equals(code)){
                JSONArray data = jsonObject.getJSONArray("data");
                if (CollectionUtils.isNotEmpty(data)){
                    for (Object o : data){
                        JSONObject jsonObject1 = (JSONObject)o;
                        BipStatus bipStatus = new BipStatus();
                        bipStatus.setBipStatus(jsonObject1.getString("billstate"));
                        JSONArray entryctrtList = jsonObject1.getJSONArray("entryctrtList");
                        if (CollectionUtils.isNotEmpty(entryctrtList)){
                            String begindate = JSON.parseObject(entryctrtList.get(0).toString()).getString("begindate");
                            bipStatus.setEntryDate(begindate.substring(0, 10));//入职日期
                        }
                        bipStatus.setId(jsonObject1.getString("entryDefines__jianliid"));//entryDefines__jianliid 简历id
                        bipStatus.setUserData(jsonObject1.getString("probationwage") + ": "+ jsonObject1.getString("formalwage"));
                        result.add(bipStatus);
                    }
                }
            }else {
                return "code" + code + "," + jsonObject.getString("message");
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    或者:

            LocalDateTime start = endTime.minusDays(15);
            Map<String,String> header = new HashMap<>();
            header.put("Authorization","Bearer "+beiSenToken);
            Map<String, Object> paramVO = new HashMap<>();
            paramVO.put("start", start);
            paramVO.put("end", endTime);
            paramVO.put("type", 3);//面试评价
            paramVO.put("batchId", "");
            String result = null;
            try {
                result = HttpClientUtil.jsonPostHeader("https://openapi.italent.cn/RecruitV6/api/v1/Interview/GetInterviewsByDate", paramVO, header);
            } catch (Exception e) {
                e.printStackTrace();
                return "指定时间获取北森面试id集合异常";
            }
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("code");
            if ("200".equals(code)){
                String data = jsonObject.getString("data");
                UserIdComBs userIdComBs = JSON.parseObject(data, UserIdComBs.class);
                userIdComBs.setTransferTime(new Date());
                String items = userIdComBs.getItems();
                List<String> list = JSON.parseArray(items, String.class);
    //            if ("true".equals(userIdComBs.getIsLastBatch())){
    //                userIdComBs.setIsLastBatch("false");
    //            }
                if (!"true".equals(userIdComBs.getIsLastBatch())){ //还有继续取
                    List<String> nextAllList = getInterviewsByDateNext(userIdComBs.getNextBatchId(), start, endTime, beiSenToken);//递归调取下一次集合
                    if (null != nextAllList){
                        list.addAll(nextAllList);
                    }else {
                        return "指定时间获取北森面试id集合异常";
                    }
                }
                return list;
            }else {
                return jsonObject.getString("message");
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    完结撒花o( ̄▽ ̄)ブ

  • 相关阅读:
    DRM全解析 —— plane详解(1)
    Vite知识体系简述
    定义头文件如何避免被重复引用
    docker(一):Develop faster. Run anywhere.
    Rancher 离线安装 longhorn 存储类
    Python实战——Selenium与iframe结合应用
    leetcode 304. Range Sum Query 2D - Immutable 二维区域和检索 - 矩阵不可变(中等)
    110-注解JSONField、DateTimeFormat、JsonFormat、JsonProperty
    Online JSON formatter for developers
    开发实战经验分享:互联网医院系统源码与在线问诊APP搭建
  • 原文地址:https://blog.csdn.net/qq_42969135/article/details/134395403