A tool class for Http requests

Don’t talk nonsense, go directly to the code

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.bccommonmodule.device.utils.SslUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/***
 * @Author: zjm
 * @Description: Send request tool class
 * @Date: 2023/3/14 15:05
 **/
public class HttpsUtils {
    private static final int MAX_TIMEOUT = 7000;
    private static final Logger logger = LoggerFactory. getLogger(HttpsUtils. class);
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;

    static {
        // set connection pool
        connMgr = new PoolingHttpClientConnectionManager();
        // Set the connection pool size
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        // Validate connections after 1 sec of inactivity
        connMgr.setValidateAfterInactivity(1000);
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // Set connection timeout
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // set read timeout
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // Set the timeout for getting a connection instance from the connection pool
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);

        requestConfig = configBuilder. build();
    }

    /**
     * HttpGet request
     * @param vurl: request address, map: {header information}
     * @return return message
     */
    public static JSONObject httpGet(String vurl,Map<String, String> map) {
        try {
            URL url = new URL(vurl);
            HttpURLConnection connection = (HttpURLConnection) url. openConnection();
            for (Map. Entry item : map. entrySet()) {
                connection.setRequestProperty(item.getKey().toString(), item.getValue().toString());//Set header
            }
            InputStream in = connection. getInputStream();
            InputStreamReader isr = new InputStreamReader(in, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br. readLine()) != null) {
                sb.append(line);
            }
            br. close();
            isr. close();
            in. close();
            return JSON. parseObject(sb. toString());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * Send GET request (HTTP), K-V form
     *
     * @param url
     * @param params
     * @return
     */
    public static JSONObject doGet(String url, Map<String, Object> params) {
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
// if (!CollectionUtils.isEmpty(params)){
// param.append("?");
// }
        for (String key : params. keySet()) {
            if (i == 0) {
                param.append("?");
                param.append(key).append("=").append(params.get(key));
            }
            else {
                param.append(" & amp;");
                param.append(key).append("=").append(params.get(key));
            }
            i + + ;
        }
        apiUrl += param;
        String result = null;
        HttpClient httpClient = null;
        try {
            if (apiUrl. startsWith("https")) {
                httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
                        .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
            } else {
                httpClient = HttpClients.createDefault();
            }

            HttpGet httpGet = new HttpGet(apiUrl);
            HttpResponse response = httpClient. execute(httpGet);
            HttpEntity entity = response. getEntity();
            if (entity != null) {
                InputStream instream = entity. getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception e) {
            logger.error("########### failed to send GET request",e);
            return null;
        }
        System.out.println(result);
        return JSON. parseObject(result);
    }

    /**
     * Send a Get request and return it as a string
     * @param url
     * @return
     */
    public static String doGetString(String url) {
        try {
            URL thisurl = new URL(url); // convert the string to URL request address
            HttpURLConnection connection = (HttpURLConnection) thisurl
                    .openConnection();// open the connection
            connection.connect();// connect session
            // get input stream
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// Loop read stream
                sb.append(line);
            }
            br.close();// close the stream
            connection.disconnect();// Disconnect

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            // System.out.println("Failed!");
            return null;
        }
    }

    /**
     * Send a POST request (HTTP) with no input data
     *
     * @param apiUrl
     * @return
     */
// public static JSONObject doPost(String apiUrl) {
// return doPost(apiUrl, new HashMap<String, Object>());
// }

    /**
     * Send POST request, K-V form
     *
     * @param apiUrl
     * API interface URL
     * @param params
     * parameter map
     * @return
     */
    public static Map doPost(String apiUrl, String params) {
        try {
            URL url = new URL(apiUrl);
            if (apiUrl. startsWith("https")) {
                SslUtils.ignoreSsl();
            }
            URLConnection u = url. openConnection();
            // Set common request attributes
            u.setRequestProperty("accept", "*/*");
            u.setRequestProperty("connection", "Keep-Alive");
            u.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            u.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            u.setDoInput(true);
            u.setDoOutput(true);
            u.setConnectTimeout(30000);
            u.setReadTimeout(30000);
            DataOutputStream out = new DataOutputStream(u
                    .getOutputStream());

            // Text, the content of the text is actually consistent with the parameter string after '? ' in the get URL
            out.write(params.getBytes("utf-8"));//"ISO-8859-1"
// out.writeBytes(URLEncoder.encode(params, "UTF-8"));
            out. flush();
            out. close();
// OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(), "UTF-8");
// osw.write(JSONObject.toJSONString(params));
// osw. flush();
// osw. close();
            u. getOutputStream();
            HttpURLConnection con = (HttpURLConnection) u;
            Map<String,String> map = new HashMap<>();
            int responseCode = con. getResponseCode();
            String s = String. valueOf(responseCode);
            map.put("code", s);
            map.put("data", IOUtils.toString(u.getInputStream()));
            out.close();// close the stream
            return map;
        } catch (Exception e) {
            logger.error("#########Failed to send POST request",e);
            return null;
        } finally {

        }

    }

    public static String doPost(String apiUrl, Map<String, Object> params) {
        try {
            URL url = new URL(apiUrl);
            if (apiUrl. startsWith("https")) {
                SslUtils.ignoreSsl();
            }
            URLConnection u = url. openConnection();
            // Set common request properties
            u.setRequestProperty("accept", "*/*");
            u.setRequestProperty("connection", "Keep-Alive");
            u.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            u.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            u.setDoInput(true);
            u.setDoOutput(true);
            u.setConnectTimeout(30000);
            u.setReadTimeout(30000);
            DataOutputStream out = new DataOutputStream(u
                    .getOutputStream());

            // Text, the content of the text is actually consistent with the parameter string after '? ' in the get URL
// out.writeBytes(params);
            out. flush();
            out. close();
// OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(), "UTF-8");
// osw.write(JSONObject.toJSONString(params));
// osw. flush();
// osw. close();
            u. getOutputStream();
            out.close();// close the stream
            return IOUtils.toString(u.getInputStream());
        } catch (Exception e) {
            logger.error("#########Failed to send POST request",e);
            return null;
        } finally {

        }

    }




    /**
     * Send POST request, K-V form
     *
     * @param apiUrl
     * API interface URL
     * @param params
     * parameter map
     * @return
     */
    public static Map<String,Object> doPostRetString(String apiUrl, Map<String, Object> params,Map<String,String> headerMap,int type){
        CloseableHttpClient httpClient = null;
        //String httpStr = null;
        CloseableHttpResponse response = null;
        try {
            if (apiUrl. startsWith("https")) {
                httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
                        .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
            } else {
                httpClient = HttpClients.createDefault();
            }

            HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setConfig(requestConfig);

            // Create HttpPost object
            // HttpPost httpPost = new HttpPost(url);
            //httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            JSONObject jsonobj = JSONObject. parseObject(JSON. toJSONString(params));
            if(1==type){
                String jsonParams = "{\\
" +
                        " "VillageInfoList":[\\
" +
                        " {\\
" +
                        " "JLXXQMC":"CGP",\\
" +
                        " "SJZT":"ZC",\\
" +
                        " "SYZTDM":"1",\\
" +
                        " "DQJD":109.182823,\\
" +
                        " "ZAGLXXSSJWZRQDM":"520603001005",\\
" +
                        " "SQXXBZ":"4205030300000100003010420200802174329135",\\
" +
                        " "DJR_GMSFZHM":"362502199508132835",\\
" +
                        " "DJR_LXDH":"18676750373",\\
" +
                        " "XQWYGS_XM":"hlj",\\
" +
                        " "XQLX":"KFS",\\
" +
                        " "XQWYGS_DWMC":"",\\
" +
                        " "DQWD":27.672497,\\
" +
                        " "XQXXBZ":"4205030300000100003010420200802174329135",\\
" +
                        " "GXSJ":"20190325181908",\\
" +
                        " "TP":"http://192.168.0.1/1.jpg",\\
" +
                        " "DZMC":"WSQ",\\
" +
                        " "SHXQLDH":"0101,0401",\\
" +
                        " "HJDZ_XZQHDM":"520603001000",\\
" +
                        " "XQBH":"THIRD-1000",\\
" +
                        " "DZBM":"520603001000",\\
" +
                        " "SJLY":"hpy",\\
" +
                        " "XQCRK_SL":2,\\
" +
                        " "XQLD_SL":2,\\
" +
                        " "DJR_XM":"admin",\\
" +
                        " "XQQY_RQ":"20200813110124",\\
" +
                        " "XQWYGS_LXDH":"18676750373"\\
" +
                        " }\\
" +
                        " ]\\
" +
                        "}";
                jsonobj = JSONObject. parseObject(jsonParams);
            }
            logger.info("Request parameters:" + jsonobj.toString());
            StringEntity se = new StringEntity(jsonobj.toString(),"utf-8");
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            if(headerMap != null & amp; & amp; headerMap. size() > 0){
                for(String key: headerMap. keySet()){
                    String value = headerMap.get(key).toString();
                    httpPost.setHeader(key,value);
                }
            }
            httpPost.setEntity(se);
            // CloseableHttpResponse response = null;

            // Send Post and return an HttpResponse object
            response = httpClient. execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode=====" + statusCode);
// logger.info("responseData=====" + EntityUtils.toString(response.getEntity(), "utf-8"));
            if (statusCode == 200 || statusCode == 401 || statusCode == 406) {
            }else{
                httpPost. abort();
                throw new RuntimeException("HttpClient, error status code :" + statusCode);
            }
            HttpEntity entity = response. getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils. consume(entity);
            Map<String,Object>dataMap = new HashMap<String,Object>();
            dataMap.put("result",JSONObject.parseObject(result));
            dataMap.put("headers",response.getAllHeaders());
            return dataMap;
        } catch (Exception e) {
            logger.error("#########Failed to send POST request", e);
            return null;
        } finally {
            if (response != null) {
                try {
                    EntityUtils. consume(response. getEntity());
                } catch (IOException e) {
                    logger.error("#########Failed to send POST request", e);
                    return null;
                }
            }
        }

            /*List<NameValuePair> pairList = new ArrayList<>(params. size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry. getKey(), entry. getValue(). toString());
                pairList. add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient. execute(httpPost);
            HttpEntity entity = response. getEntity();
            retValue = EntityUtils.toString(entity, "UTF-8");*/
    }

    /**
     * Send a POST request in JSON form
     *
     * @param apiUrl
     * @param json
     * json object
     * @return
     */
    public static JSONObject doPost(String apiUrl, Object json) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String httpStr = null;
        try {
            if (apiUrl. startsWith("https")) {
                httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
                        .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
            } else {
                httpClient = HttpClients.createDefault();
            }

            httpPost = new HttpPost(apiUrl);
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// Solve the Chinese garbled problem
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient. execute(httpPost);
            HttpEntity entity = response. getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.error("#########Failed to send POST request",e);
            return null;
        } finally {
            if (response != null) {
                try {
                    EntityUtils. consume(response. getEntity());
                } catch (IOException e) {
                    logger.error("#########Failed to send POST request",e);
                    return null;
                }
            }
        }
        return JSON. parseObject(httpStr);
    }

    /**
     * Create an SSL secure connection
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLConnSocketFactory() throws Exception {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        } catch (GeneralSecurityException e) {
            logger.error("#########Create SSL secure connection",e);
            throw new Exception(e. getMessage());
        }
        return sslsf;
    }

    /**
     * Send a POST request in JSON format
     *
     * @param apiUrl
     * @param json
     * json object
     * @param params header
     * @return
     */
    public static JSONObject doPost(String apiUrl, Object json,Map<String, String> params) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String httpStr = null;
        try {
            if (apiUrl. startsWith("https")) {
                httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
                        .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
            } else {
                httpClient = HttpClients.createDefault();
            }

            httpPost = new HttpPost(apiUrl);
            httpPost.setConfig(requestConfig);
            if(!params.isEmpty()){
                for(Entry<String,String> entry:params. entrySet()){
                    httpPost.addHeader(entry.getKey(),entry.getValue());
                }
            }
            logger.info("Request parameters:" + JSONObject.toJSONString(json));
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// Solve the Chinese garbled problem
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient. execute(httpPost);
            HttpEntity entity = response. getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.error("#########Failed to send POST request",e);
            return null;
        } finally {
            if (response != null) {
                try {
                    EntityUtils. consume(response. getEntity());
                } catch (IOException e) {
                    logger.error("#########Failed to send POST request",e);
                    return null;
                }
            }
        }
        return JSON. parseObject(httpStr);
    }


    public static JSONObject doGet(String apiUrl, Object json,Map<String, String> params) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        String httpStr = null;
        try {
            if (apiUrl. startsWith("https")) {
                httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
                        .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
            } else {
                httpClient = HttpClients.createDefault();
            }

            httpGet = new HttpGet(apiUrl);
            httpGet.setConfig(requestConfig);
            if(!params.isEmpty()){
                for(Entry<String,String> entry:params. entrySet()){
                    httpGet.addHeader(entry.getKey(),entry.getValue());
                }
            }
            logger.info("Request parameters:" + JSONObject.toJSONString(json));
            response = httpClient. execute(httpGet);
            HttpEntity entity = response. getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.error("#########Failed to send POST request",e);
            return null;
        } finally {
            if (response != null) {
                try {
                    EntityUtils. consume(response. getEntity());
                } catch (IOException e) {
                    logger.error("#########Failed to send POST request",e);
                    return null;
                }
            }
        }
        return JSON. parseObject(httpStr);
    }
}