高性能高可用的全能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;
    }
}

二、主体代码

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];
    }
}

三、应用例子

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

或者

        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");
        }

或者:

        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");
        }

完结撒花o( ̄▽ ̄)ブ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Go语言标准库中的"net/http"包来实现高性能HTTP客户端,并且支持连接复用。 可以使用http.Transport结构体来设置连接池,并调用http.Client结构体的Do()方法来发送HTTP请求。 例如: ``` tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("http://example.com") ``` 这样就可以使用连接池来管理连接,并且可以复用连接来提高性能。 ### 回答2: 使用Golang实现高性能HTTP客户端并支持连接复用可以通过以下步骤来实现: 1. 利用Golang的net/http包创建一个基本的HTTP客户端。 2. 在发送HTTP请求之前,确定是否已经有可用的连接可以复用。可以使用sync.Pool来管理并重用连接。 3. 如果有可用的连接,从连接池中获取一个连接,否则创建一个新的连接。 4. 发送HTTP请求并获取响应。 5. 处理响应并确认是否可以复用连接。在头部检查`Connection`标头是否为`keep-alive`,或者可以使用`Transport.DisableKeepAlives`方法来强制关闭连接。 6. 将连接放回连接池中以备下次使用。 下面是一个简单的示例代码,实现了一个支持连接复用的高性能HTTP客户端: ```go package main import ( "fmt" "io/ioutil" "net/http" "sync" "time" ) var client *http.Client var pool sync.Pool func init() { transport := &http.Transport{ MaxIdleConns: 10, // 连接池最大空闲连接数 IdleConnTimeout: 30 * time.Second, // 空闲连接的超时时间 DisableKeepAlives: false, // 是否允许连接复用 MaxIdleConnDuration: 0, } client = &http.Client{Transport: transport} pool = sync.Pool{ New: func() interface{} { return client }, } } func main() { url := "http://example.com" resp, err := sendRequest(url) if err != nil { fmt.Println("请求发送失败:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取响应失败:", err) return } fmt.Println("响应数据:", string(body)) } func sendRequest(url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Add("Connection", "keep-alive") client := pool.Get().(*http.Client) defer pool.Put(client) return client.Do(req) } ``` 这个示例代码实现了一个HTTP客户端,该客户端支持连接复用,并使用连接池来管理连接的创建和重用。在`sendRequest`函数中,我们从连接池中获取一个连接,发送HTTP请求,然后将连接放回连接池以备下次使用。这样可以提高性能并减少连接的创建和销毁开销。 需要注意的是,为了实现连接复用,我们在创建http.Transport时将DisableKeepAlives设置为false,并在发送请求时添加Connection标头并设置为keep-alive。这样服务器端在响应后会保持连接,允许客户端复用该连接。 ### 回答3: 使用Golang实现高性能HTTP客户端并支持连接复用,可以通过以下几个步骤实现: 1. 使用`http.Transport`结构体创建一个HTTP传输对象,并设置相关参数。在这个对象中,可以使用`MaxIdleConns`参数设置空闲连接的最大数量,以及`MaxIdleConnsPerHost`参数设置每个主机的最大空闲连接数量。 2. 创建一个`http.Client`对象,并将前面创建的传输对象传递给它,以便进行HTTP请求。还可以设置其他相关的客户端参数,如超时时间等。 3. 使用`client.Do(request)`方法向服务器发送HTTP请求,并获取响应。这个方法返回一个`http.Response`对象,其中包含了响应的状态码、头部信息、响应体等。 4. 使用完毕后,需要调用`response.Body.Close()`方法关闭响应体,以释放资源。 5. 为了实现连接的复用,可以在多个请求之间共享`http.Client`对象,而不是每次请求都创建一个新的对象。这样,连接池中的连接就可以被复用,提高性能。 6. 在多个并发请求的情况下,可以使用协程来发送并发请求,确保每个请求都可以重用连接并独立工作。 综上所述,通过上述步骤,可以使用Golang实现一个高性能HTTP客户端,并支持连接的复用,从而提高性能和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值