记一个httputil

``

import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.*;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
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.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

/**
 * @date 2021-10-13
 * @Description: httpclient 工具类
 */
public class HttpUtil {

    private static final int MAX_TOTAL = 50;

    private static final int MAX_PERROUTE = 20;

    private static final int EXECUTION_COUNT = 3;

    /**
     * 忽略证书
     * @return
     */
    public static CloseableHttpClient createSSLClientDefault() {
        try {
            //使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            //NoopHostnameVerifier类:  作为主机名验证工具,实质上关闭了主机名验证,它接受任何
            //有效的SSL会话并匹配到目标主机。
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    /**
     * GET 请求
     * @param url         请求的URL
     * @param headers     请求头
     * @param connectTime 连接超时时间 单位 ms
     * @throws ParseException
     */
    public static String get(String url, Map<String, String> headers, Integer connectTime, Integer socketTimeout,
                             Boolean isRetry, Integer retryCount) throws IOException, org.apache.http.conn.HttpHostConnectException,
            ParseException {

        // 默认连接时间 ms
        int cTimeout = 5000;
        // 默认的读取时间 ms
        int sTimeout = 5000;

        if (connectTime != null) {
            cTimeout = connectTime.intValue();
        }

        if (socketTimeout != null) {
            sTimeout = socketTimeout.intValue();
        }

        CloseableHttpClient httpClient = getCloseableHttpClient(isRetry, retryCount);

        RequestConfig config = null;
        config = RequestConfig.custom().setConnectTimeout(cTimeout).setSocketTimeout(sTimeout).build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(config);

        if (null != headers) {
            Set<Entry<String, String>> entrys = headers.entrySet();
            for (Entry<String, String> each : entrys) {
                httpGet.setHeader(each.getKey(), each.getValue());
            }
        }

        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity == null) {
            return null;
        }
        String strResult = EntityUtils.toString(entity);
        // 关闭连接,释放资源
        if (response != null) {
            response.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }

        return strResult;

    }

    public static CloseableHttpClient getCloseableHttpClient(final Boolean isRetry, final Integer retryCount) {

        HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

                final int retryCount_ = (null == retryCount ? EXECUTION_COUNT : retryCount);

                // System.out.println("executionCount>>>>>>>>>" +
                // executionCount);

                if (null != isRetry && isRetry == true) {
                    if (executionCount > retryCount_) {
                        // Do not retry if over max retry count
                        return false;
                    }
                }
                if (exception instanceof SocketTimeoutException) {
                    System.out.println("Sockettimout retry>>>>>>>>");
                    // Timeout
                    return true;
                }
                if (exception instanceof org.apache.http.conn.ConnectTimeoutException) {
                    System.out.println("ConnectTimeoutException retry>>>>>>>>");
                    // Timeout
                    return true;
                }

                if (exception instanceof InterruptedIOException) {
                    // Timeout
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // Unknown host
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // Connection refused
                    System.out.println(" org.apache.commons.httpclient.ConnectTimeoutException  retry.....");
                    return true;
                }

                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // Retry if the request is considered idempotent
                    return true;
                }
                return false;
            }
        };
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(MAX_TOTAL);
        // 个路由基础的连接
        cm.setDefaultMaxPerRoute(MAX_PERROUTE);
        // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
        SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
                .setSoTimeout(5000).setTcpNoDelay(true).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultSocketConfig(socketConfig)
                .setRetryHandler(retryHandler).setConnectionManager(cm).build();

        return httpClient;
    }

    public static String sendHttpDelete(String url) throws ClientProtocolException, IOException, ParseException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig config = null;
        try {
            // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
            SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1)
                    .setSoReuseAddress(true).setSoTimeout(5000).setTcpNoDelay(true).build();
            httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
            // 创建默认的httpClient实例.
            // httpClient = HttpClients.createDefault();
            int connectTimeout = 5000;
            int socketTimeout = 20000;
            config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                    .build();
            httpDelete.setConfig(config);
            // 执行请求
            response = httpClient.execute(httpDelete);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } finally {
            // 关闭连接,释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return responseContent;
    }

    // public static String sendHttpPost(String httpUrl, Map<String, Object> maps) {
    // HttpPost httpPost = new HttpPost(httpUrl);
    // RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(20000).build();
    // httpPost.setConfig(config);
    // // 创建参数队列
    // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    // for (String key : maps.keySet()) {
    // if ("Cookie".equals(key)) {
    // httpPost.setHeader("Cookie", maps.get(key).toString());
    // } else {
    // nameValuePairs.add(new BasicNameValuePair(key, maps.get(key).toString()));
    // }
    // }
    // try {
    // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return sendHttpPost(httpPost);
    // }

    // public static String sendHttpPost(String httpUrl, Map<String, String> maps, Integer connTimeout, Integer
    // readTimeout) {
    // HttpPost httpPost = new HttpPost(httpUrl);
    // // 创建参数队列
    // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    // for (String key : maps.keySet()) {
    // nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
    // }
    // try {
    // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return sendHttpPost(httpPost, connTimeout, readTimeout);
    // }

    // private static String sendHttpPost(HttpPost httpPost, Integer connTimeout, Integer readTimeout) {
    // CloseableHttpClient httpClient = null;
    // CloseableHttpResponse response = null;
    // HttpEntity entity = null;
    // String responseContent = null;
    //
    // RequestConfig config = RequestConfig.custom().setConnectTimeout(null == connTimeout ? 5000 :
    // connTimeout).setSocketTimeout(null == readTimeout ? 20000 : readTimeout)
    // .build();
    // httpPost.setConfig(config);
    // try {
    // // 创建默认的httpClient实例.
    // httpClient = HttpClients.createDefault();
    // // 执行请求
    // response = httpClient.execute(httpPost);
    // entity = response.getEntity();
    // responseContent = EntityUtils.toString(entity, "UTF-8");
    // } catch (Exception e) {
    // e.printStackTrace();
    // } finally {
    // try {
    // // 关闭连接,释放资源
    // if (response != null) {
    // response.close();
    // }
    // if (httpClient != null) {
    // httpClient.close();
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // }
    // return responseContent;
    // }

    /**
     * @param httpUrl 请求路径
     * @param params  请求参数
     * @param headers 请求头
     * @throws IOException
     * @throws ClientProtocolException
     * @throws ParseException
     * @Description 发送POST请求
     * @author renxutong
     */
    public static String sendHttpPost(String httpUrl, Map<String, Object> params, Map<String, String> headers)
            throws ClientProtocolException, IOException, ParseException {
        int connectTimeout = 5000;
        int socketTimeout = 20000;
        RequestConfig config = null;

        config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                .setRedirectsEnabled(true).build();
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost.setConfig(config);
        if (params != null) {
            // 创建参数队列
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (Entry<String, Object> entry : params.entrySet()) {
                String value = entry.getValue() == null ? "" : entry.getValue().toString();
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        }
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return sendHttpPost(httpPost);
    }

    private static String sendHttpPost(HttpPost httpPost) throws ClientProtocolException, IOException {
        //CloseableHttpClient httpClient = null;
        CloseableHttpClient httpClient = createSSLClientDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
//            SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1)
//                    .setSoReuseAddress(true).setSoTimeout(5000).setTcpNoDelay(true).build();
//            httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
            // 创建默认的httpClient实例.
            // httpClient = HttpClients.createDefault();
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } finally {
            // 关闭连接,释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return responseContent;
    }

    /**
     * @param httpUrl    请求路径
     * @param params     请求参数
     * @param headers    请求头
     * @param headerName 返回的响应头内容
     * @throws ParseException
     * @throws IOException
     * @throws ClientProtocolException
     * @Description POST请求
     * @author renxutong
     */
    public static Map<String, String> sendHttpPost(String httpUrl, Map<String, Object> params,
                                                   Map<String, String> headers, String headerName) throws ParseException, ClientProtocolException, IOException {
        int connectTimeout = 5000;
        int socketTimeout = 20000;
        RequestConfig config = null;
        config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost.setConfig(config);
        if (params != null) {
            // 创建参数队列
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (Entry<String, Object> entry : params.entrySet()) {
                String value = entry.getValue() == null ? "" : entry.getValue().toString();
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        }
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return sendHttpPost(httpPost, headerName);
    }

    public static Map<String, String> sendHttpPostWithRedirect(String httpUrl, Map<String, Object> params,
                                                               Map<String, String> headers, String headerName) throws ParseException, ClientProtocolException, IOException {
        int connectTimeout = 5000;
        int socketTimeout = 20000;
        RequestConfig config = null;
        config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                .setRedirectsEnabled(true).build();
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost.setConfig(config);
        if (params != null) {
            // 创建参数队列
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (Entry<String, Object> entry : params.entrySet()) {
                String value = entry.getValue() == null ? "" : entry.getValue().toString();
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        }
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return sendHttpPost(httpPost, headerName);
    }

    public static CloseableHttpClient getHttpClient() {
        // HttpClient httpClient = HttpClientBuilder.create().build();
        // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
        SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
                .setSoTimeout(5000).setTcpNoDelay(true).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
        return httpClient;
    }


    /**
     * @param url     请求路径
     * @param headers
     * @return
     * @throws ParseException
     * @throws IOException
     * @throws ClientProtocolException
     * @Description GET请求
     * @author renxutong
     */
    public static String get(String url, Map<String, String> params, Map<String, String> headers)
            throws ParseException, ClientProtocolException, IOException {
        //CloseableHttpClient httpClient = null;
        CloseableHttpClient httpClient = createSSLClientDefault();
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        try {
            //httpClient = getHttpClient();
            // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
            if (params != null) {
                StringBuilder sb = new StringBuilder("?");
                for (Entry<String, String> entry : params.entrySet()) {
                    String value = URLEncoder.encode(entry.getValue(), "UTF-8");
                    // 解决URLEncoder.encode方法将空格转义为“+”号
                    value = value.replaceAll("\\+", "%20");
                    sb.append(entry.getKey()).append("=").append(value).append("&");
                }
                sb.delete(sb.length() - 1, sb.length());
                url += sb.toString();
            }
            int connectTimeout = 5000;
            int socketTimeout = 20000;
            RequestConfig config = null;
            config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                    .build();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(config);
            if (headers != null) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            if (entity.isStreaming()) {
                inputStream = entity.getContent();
                if (inputStream != null) {
                    return consumeInputStream(inputStream);
                }
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return null;
    }
    
    /**
     * @param httpPost
     * @param headerName 要返回的响应头
     * @throws IOException
     * @throws ClientProtocolException
     * @Description POST请求
     * @author renxutong
     */
    private static Map<String, String> sendHttpPost(HttpPost httpPost, String headerName)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
            SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1)
                    .setSoReuseAddress(true).setSoTimeout(5000).setTcpNoDelay(true).build();
            httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
            // 创建默认的httpClient实例.
            // httpClient = HttpClients.createDefault();
            // 执行请求
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            map.put("content", responseContent);
            Header[] responseHeaders = response.getHeaders(headerName);
            if (responseHeaders != null && responseHeaders.length > 0) {
                String headerValue = responseHeaders[0].getValue();
                map.put(headerName, headerValue);
            }
        } finally {
            // 关闭连接,释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return map;
    }

    /**
     * http put 方法,json类型参数
     * @param url
     * @param jsonParam
     * @param isRetry
     * @param retryCount
     * @throws IOException
     * @throws ClientProtocolException
     * @throws ParseException
     */
    public static String putJson(String url, JSONObject jsonParam, Boolean isRetry, Integer retryCount)
            throws ClientProtocolException, IOException, ParseException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        try {
            httpClient = getCloseableHttpClient(isRetry, retryCount);
            int connectTimeout = 5000;
            int socketTimeout = 20000;
            RequestConfig config = null;
            config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                    .build();
            HttpPut httpPut = new HttpPut(url);
            httpPut.setConfig(config);
            httpPut.setHeader("Accept", "application/json");

            StringEntity se = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpPut.setEntity(se);

            response = httpClient.execute(httpPut);
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            if (entity.isStreaming()) {
                inputStream = entity.getContent();
                if (inputStream != null) {
                    return consumeInputStream(inputStream);
                }
            }
        } finally {
            // 关闭连接,释放资源
            if (inputStream != null) {
                inputStream.close();
            }
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return null;
    }

    /**
     * http post 方法,json类型参数
     * @param url
     * @param requestBody json对象
     * @return String
     * @throws IOException
     * @throws ClientProtocolException
     * @throws ParseException
     */
    public static String postJson(String url, String requestBody,Map<String, String> headers) throws ClientProtocolException, IOException, ParseException {
//        CloseableHttpClient httpClient = null;
        CloseableHttpClient httpClient = createSSLClientDefault();
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        try {
            // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
//            SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
//                    .setSoTimeout(5000).setTcpNoDelay(true).build();
//            httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
            // httpClient = getCloseableHttpClient(isRetry, retryCount);
            int connectTimeout = 5000;
            int socketTimeout = 20000;
            RequestConfig config = null;
            config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                    .build();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(config);
            httpPost.setHeader("Accept", "application/json");

            StringEntity se = new StringEntity(requestBody, "utf-8");// 解决中文乱码问题
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpPost.setEntity(se);

            if (!CollectionUtils.isEmpty(headers)) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            if (entity.isStreaming()) {
                inputStream = entity.getContent();
                if (inputStream != null) {
                    return consumeInputStream(inputStream);
                }
            }
        } finally {
            // 关闭连接,释放资源
            if (inputStream != null) {
                inputStream.close();
            }
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return null;
    }

    /**
     * http get 方法,获取json结果
     * @param url        地址
     * @return String
     * @throws IOException
     * @throws ClientProtocolException
     * @throws ParseException
     */
    public static String getJson(String url, Map<String, String> headers) throws ClientProtocolException, IOException, ParseException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        try {
            // 设置SocketConfig解决程序卡死在HttpClient.execute()方法执行处
            SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
                    .setSoTimeout(5000).setTcpNoDelay(true).build();
            httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
            // httpClient = getCloseableHttpClient(isRetry, retryCount);
            int connectTimeout = 5000;
            int socketTimeout = 20000;
            RequestConfig config;
            config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                    .build();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(config);
            httpGet.setHeader("Accept", "application/json");

            if (!CollectionUtils.isEmpty(headers)) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            if (entity.isStreaming()) {
                inputStream = entity.getContent();
                if (inputStream != null) {
                    return consumeInputStream(inputStream);
                }
            }
        } finally {
            // 关闭连接,释放资源
            if (inputStream != null) {
                inputStream.close();
            }
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return null;
    }

    private static String consumeInputStream(InputStream in) throws IOException {

        StringBuilder out = new StringBuilder();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

    /**
     * 表单形式上传数据
     *
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @return 返回response数据
     */
    @SuppressWarnings("rawtypes")
    public static JSONObject doPost(String urlStr, Map<String, String> textMap, Map<String, MultipartFile> fileMap) {
        JSONObject jsonObject = null;
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    MultipartFile inputValue = (MultipartFile) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    String filename = inputValue.getOriginalFilename();

                    // 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                    String contentType = inputValue.getContentType();

                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\";filename=\"" + filename
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    InputStream in = inputValue.getInputStream();
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            InputStream inputStream = null;
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK ) {
                inputStream = conn.getErrorStream();//主要就是这里
            } else {
                inputStream = conn.getInputStream();//主要就是这里
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            String result = new String(buffer);
            jsonObject = JSONObject.parseObject(result);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return jsonObject;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值