• HttpClinet工具类


    一、URL调用 忽略https证书

    1、调用

    InputStream in = null;
    
            try {
                URL url = new URL( "url地址" );
                IgnoreSSL ignoreSSL = new IgnoreSSL(url);
                in = ignoreSSL.getSteam();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String count = "";
            try {
                byte[] b = new byte[1024];
                int len;
                while ((len = in.read(b))!=-1) {
                    count+=new String(b,0,len);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

    2、url忽略https工具类

    public class IgnoreSSL {
        private HttpURLConnection connection;
        public ignoreSSL(final URL validationUrl) throws Exception {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            connection = (HttpURLConnection) validationUrl.openConnection();
        }
        public InputStream getSteam() throws IOException {
            return connection.getInputStream();
        }
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                        + session.getPeerHost());
                return true;
            }
        };
    
        private static void trustAllHttpsCertificates() throws Exception {
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
            javax.net.ssl.TrustManager tm = new miTM();
            trustAllCerts[0] = tm;
            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                    .getInstance("SSL");
            sc.init(null, trustAllCerts, null);
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                    .getSocketFactory());
        }
    
        static class miTM implements javax.net.ssl.TrustManager,
                javax.net.ssl.X509TrustManager {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
    
            public boolean isServerTrusted(
                    java.security.cert.X509Certificate[] certs) {
                return true;
            }
    
            public boolean isClientTrusted(
                    java.security.cert.X509Certificate[] certs) {
                return true;
            }
    
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
    
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
        }
    
    }

    二、HttpClinet 工具类

    import java.io.IOException;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    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.utils.URIBuilder;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    public class HttpClientUtil {
    
        private HttpClientUtil() {
        }
    
        public static String doGet(String url, Map<String, String> param) {
    
            // 创建Httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
    
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 创建uri
                URIBuilder builder = new URIBuilder(url);
                if (param != null) {
                    for (String key : param.keySet()) {
                        builder.addParameter(key, param.get(key));
                    }
                }
                URI uri = builder.build();
    
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(uri);
    
                // 执行请求
                response = httpclient.execute(httpGet);
                // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
    
        public static String doGet(String url) {
            return doGet(url, null);
        }
    
        public static String doPost(String url, Map<String, Object> param) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建参数列表
                if (param != null) {
                    List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : param.keySet()) {
                        paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                    httpPost.setEntity(entity);
                }
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return resultString;
        }
    
        public static String doPost(String url) {
            return doPost(url, null);
        }
    
        public static String doPostJson(String url, String json,String token_header) throws Exception {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建请求内容
                httpPost.setHeader("HTTP Method","POST");
                httpPost.setHeader("Connection","Keep-Alive");
                httpPost.setHeader("Content-Type","application/json;charset=utf-8");
                httpPost.setHeader("x-authentication-token",token_header);
    
                StringEntity entity = new StringEntity(json);
    
                entity.setContentType("application/json;charset=utf-8");
                httpPost.setEntity(entity);
    
                // 执行http请求
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                throw e;
            } finally {
                try {
                    if(response!=null){
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return resultString;
        }
    
        public static String postXML(String url,String xml){
            CloseableHttpClient client = null;
            CloseableHttpResponse resp = null;
            try{
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
                client = HttpClients.createDefault();
                StringEntity entityParams = new StringEntity(xml,"utf-8");
                httpPost.setEntity(entityParams);
                client = HttpClients.createDefault();
                resp = client.execute(httpPost);
                String resultMsg = EntityUtils.toString(resp.getEntity(),"utf-8");
                return resultMsg;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if(client!=null){
                        client.close();
                    }
                    if(resp != null){
                        resp.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
    
    }

    解析xml

    import com.alibaba.fastjson.JSON;
    import org.dom4j.*;
    
    import java.util.*;
    
    public class XmlStr {
    
        public static void main(String[] args) throws Exception {
    
            String xmlStr = "<returnInfo><resultInfo><returnCode>SUC</returnCode><codeDesc>成功</codeDesc></resultInfo><routeInfo><maxRate>2048</maxRate></routeInfo></returnInfo>";
            Map<String, String> retMap = iterateWholeXML(xmlStr);
    
            /*Map<String, String> retMap = new HashMap<String, String>();
            for (int i = 0; i < resultList.size(); i++) {
                Map map = (Map) resultList.get(i);
    
                for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                    String key = (String) iterator.next();
                    retMap.put(key, (String) map.get(key));
    
                }
            }*/
            System.out.println("reMap" + retMap);
    
        }
    
        /**
         * 递归解析任意的xml 遍历每个节点和属性
         *
         * @param xmlStr
         */
        public static Map<String, String> iterateWholeXML(String xmlStr) {
    
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    
            try {
                Document document = DocumentHelper.parseText(xmlStr);
                Element root = document.getRootElement();
                recursiveNode(root, list);
                Map<String, String> retMap = new HashMap<String, String>();
                for (int i = 0; i < list.size(); i++) {
                    Map map = (Map) list.get(i);
    
                    for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                        String key = (String) iterator.next();
                        retMap.put(key, (String) map.get(key));
    
                    }
                }
                String s = JSON.toJSONString(retMap);
                System.out.println(s);
                return retMap;
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 递归遍历所有的节点获得对应的值
         *
         * @param
         */
        private static void recursiveNode(Element root, List<Map<String, String>> list) {
    
            // 遍历根结点的所有孩子节点
            HashMap<String, String> map = new HashMap<String, String>();
            for (Iterator iter = root.elementIterator(); iter.hasNext();) {
                Element element = (Element) iter.next();
                if (element == null)
                    continue;
                // 获取属性和它的值
                for (Iterator attrs = element.attributeIterator(); attrs.hasNext();) {
                    Attribute attr = (Attribute) attrs.next();
                    System.out.println(attr);
                    if (attr == null)
                        continue;
                    String attrName = attr.getName();
                    System.out.println("attrname" + attrName);
                    String attrValue = attr.getValue();
    
                    map.put(attrName, attrValue);
                }
                // 如果有PCDATA,则直接提出
                if (element.isTextOnly()) {
                    String innerName = element.getName();
                    String innerValue = element.getText();
    
                    map.put(innerName, innerValue);
                    list.add(map);
                } else {
                    // 递归调用
                    recursiveNode(element, list);
                }
            }
        }
    
    }

    三、HttpsClient工具类

    最简单的方法是忽略ssl证书并信任任何连接。这种方法对于生产代码不可接受,因为它违反了使用HTTPS的目的。但是,在某些用例中,如果您想快速尝试一些事情,可以采用这种方法。

    信任任何证书方法(简单,不建议用于生产代码。)

    import javax.net.ssl.SSLContext;
    import javax.net.ssl.X509TrustManager;
    
    import org.apache.http.client.HttpClient;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContexts;
    
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    
    import java.security.SecureRandom;
    
    public class HttpClientFactory {
    
        private static CloseableHttpClient client;
    
        public static HttpClient getHttpsClient() throws Exception {
    
            if (client != null) {
                return client;
            }
            SSLContext sslcontext = SSLContexts.custom().useSSL().build();
            sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                    SSLConnectionSocketFactory.BROWSER\_COMPATIBLE\_HOSTNAME\_VERIFIER);
            client = HttpClients.custom().setSSLSocketFactory(factory).build();
    
            return client;
        }
    
        public static void releaseInstance() {
            client = null;
        }
    }

    上面的方法将返回httpClient对象,该对象可用于进行任何HTTPS调用。从现在开始执行HTTPS调用与进行HTTP调用没有什么不同。因此,您可以为工厂提供两种方法,一种用于安全,另一种用于非安全。

    在这里,我们使用了HttpsTrustManager,它只不过是分散所有客户端而已。只需实现X509TrustManager并自动生成所有方法即可完成。

    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.X509TrustManager;
    
    public class HttpsTrustManager implements X509TrustManager {
    
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    
    }

    导入密钥库(推荐)

    如果您要编写产品质量代码,则应该考虑这种方法。在您的应用程序中拥有所有密钥,并使用这些密钥库创建一个SSLContext。然后可以将创建的SSLContext注入SSLConnectionSocketFactory,其余步骤将相同。

    import javax.net.ssl.SSLContext;
    
    import org.apache.http.client.HttpClient;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContexts;
    
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.KeyManagementException;
    
    public class HttpClientFactory {
    
        private static CloseableHttpClient client;
    
        public static HttpClient getHttpsClient() throws Exception {
    
            if (client != null) {
                return client;
            }
            SSLContext sslcontext = getSSLContext();
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                    SSLConnectionSocketFactory.BROWSER\_COMPATIBLE\_HOSTNAME\_VERIFIER);
            client = HttpClients.custom().setSSLSocketFactory(factory).build();
    
            return client;
        }
    
        public static void releaseInstance() {
            client = null;
        }
    
        private SSLContext getSSLContext() throws KeyStoreException, 
        NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
            KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(new File("my.keystore"));
            try {
                trustStore.load(instream, "nopassword".toCharArray());
            } finally {
                instream.close();
            }
            return SSLContexts.custom()
                    .loadTrustMaterial(trustStore)
                    .build();
        }
    }

    两种方法之间的唯一区别是创建SSLContext的方式。

    四、SpringBoot  RestTemplate

    import org.springframework.http.*;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    
    public class HttpClient {
    
    
    
        /**
         * post
         * @param url       url
         * @param params    params
         * @return  AdToutiaoJsonTokenData
         */
        public static String sendPostRequest(String url, MultiValueMap<String, String> params){
            RestTemplate client = new RestTemplate();
            //新建Http头,add方法可以添加参数
            HttpHeaders headers = new HttpHeaders();
            //设置请求发送方式
            HttpMethod method = HttpMethod.POST;
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //将请求头部和参数合成一个请求
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            //执行HTTP请求,将返回的结构使用String 类格式化(可设置为对应返回值格式的类)
            ResponseEntity<String> response = client.exchange(url, method, requestEntity,String .class);
    
            return response.getBody();
        }
    
        /**
         * 向目的URL发送get请求
         * @param url       目的url
         * @param params    发送的参数
         * @param headers   发送的http头,可在外部设置好参数后传入
         * @return  String
         */
        public static String sendGetRequest(String url, MultiValueMap<String, String> params,HttpHeaders headers){
            RestTemplate client = new RestTemplate();
    
            HttpMethod method = HttpMethod.GET;
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //将请求头部和参数合成一个请求
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            //执行HTTP请求,将返回的结构使用String 类格式化
            ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
    
            return response.getBody();
        }
      
    public GetUuidResponseVo getId(){
    RequestIDVO requestIDVO = new RequestIDVO();
    requestIDVO.setName(ruquestIDEnum.getName());
    requestIDVO.setPlatId(ruquestIDEnum.getPlatId());
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    Gson gson = new Gson();
    HttpEntity<String> formEntity = new HttpEntity<String>(gson.toJson(requestIDVO), headers);
    String result = restTemplate.postForObject(ruquestIDEnum.getUrl(), formEntity, String.class);
    GetUuidResponseVo getUuidResponseVo = gson.fromJson(result,GetUuidResponseVo.class);
    return getUuidResponseVo;
    }
    }

    RestTemplate 工具类

    package javax.utils;
    
    import java.util.Map;
    
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;
    
    /**
     * RestTemplate 远程调用工具类
     *
     */
    public class RestTemplateUtils {
    
        private static final RestTemplate restTemplate = new RestTemplate();
    
        // ----------------------------------GET-------------------------------------------------------
    
        /**
         * GET请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, Class<T> responseType) {
            return restTemplate.getForEntity(url, responseType);
        }
    
        /**
         * GET请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Object... uriVariables) {
            return restTemplate.getForEntity(url, responseType, uriVariables);
        }
    
        /**
         * GET请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Map<String, ?> uriVariables) {
            return restTemplate.getForEntity(url, responseType, uriVariables);
        }
    
        /**
         * 带请求头的GET请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return get(url, httpHeaders, responseType, uriVariables);
        }
    
        /**
         * 带请求头的GET请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) {
            HttpEntity<?> requestEntity = new HttpEntity<>(headers);
            return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的GET请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return get(url, httpHeaders, responseType, uriVariables);
        }
    
        /**
         * 带请求头的GET请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<?> requestEntity = new HttpEntity<>(headers);
            return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables);
        }
    
        // ----------------------------------POST-------------------------------------------------------
    
        /**
         * POST请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @return
         */
        public static <T> ResponseEntity<T> post(String url, Class<T> responseType) {
            return restTemplate.postForEntity(url, HttpEntity.EMPTY, responseType);
        }
    
        /**
         * POST请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) {
            return restTemplate.postForEntity(url, requestBody, responseType);
        }
    
        /**
         * POST请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
            return restTemplate.postForEntity(url, requestBody, responseType, uriVariables);
        }
    
        /**
         * POST请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            return restTemplate.postForEntity(url, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的POST请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return post(url, httpHeaders, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的POST请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
            return post(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的POST请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return post(url, httpHeaders, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的POST请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
            return post(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 自定义请求头和请求体的POST请求调用方式
         * 
         * @param url 请求URL
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
            return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 自定义请求头和请求体的POST请求调用方式
         * 
         * @param url 请求URL
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
            return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables);
        }
    
        // ----------------------------------PUT-------------------------------------------------------
    
        /**
         * PUT请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, Class<T> responseType, Object... uriVariables) {
            return put(url, HttpEntity.EMPTY, responseType, uriVariables);
        }
    
        /**
         * PUT请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
            return put(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * PUT请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
            return put(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的PUT请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return put(url, httpHeaders, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的PUT请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
            return put(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的PUT请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return put(url, httpHeaders, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的PUT请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
            return put(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 自定义请求头和请求体的PUT请求调用方式
         * 
         * @param url 请求URL
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
            return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 自定义请求头和请求体的PUT请求调用方式
         * 
         * @param url 请求URL
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> put(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
            return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
        }
    
        // ----------------------------------DELETE-------------------------------------------------------
    
        /**
         * DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Class<T> responseType, Object... uriVariables) {
            return delete(url, HttpEntity.EMPTY, responseType, uriVariables);
        }
    
        /**
         * DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Class<T> responseType, Map<String, ?> uriVariables) {
            return delete(url, HttpEntity.EMPTY, responseType, uriVariables);
        }
    
        /**
         * DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
            return delete(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
            return delete(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return delete(url, httpHeaders, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
            return delete(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return delete(url, httpHeaders, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
            return delete(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return delete(url, httpHeaders, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
            return delete(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            return delete(url, httpHeaders, requestBody, responseType, uriVariables);
        }
    
        /**
         * 带请求头的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param headers 请求头参数
         * @param requestBody 请求参数体
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
            return delete(url, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 自定义请求头和请求体的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
            return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 自定义请求头和请求体的DELETE请求调用方式
         * 
         * @param url 请求URL
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> delete(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
            return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
        }
    
        // ----------------------------------通用方法-------------------------------------------------------
    
        /**
         * 通用调用方式
         * 
         * @param url 请求URL
         * @param method 请求方法类型
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,按顺序依次对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
            return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 通用调用方式
         * 
         * @param url 请求URL
         * @param method 请求方法类型
         * @param requestEntity 请求头和请求体封装对象
         * @param responseType 返回对象类型
         * @param uriVariables URL中的变量,与Map中的key对应
         * @return ResponseEntity 响应对象封装类
         */
        public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
            return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
        }
    
        /**
         * 获取RestTemplate实例对象,可自由调用其方法
         * 
         * @return RestTemplate实例对象
         */
        public static RestTemplate getRestTemplate() {
            return restTemplate;
        }
    
    }

    spring - RestTemplate  http

    import com.alibaba.fastjson.JSONObject;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.client.ClientHttpResponse;
    import org.springframework.http.client.SimpleClientHttpRequestFactory;
    import org.springframework.http.converter.StringHttpMessageConverter;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.ResponseErrorHandler;
    import org.springframework.web.client.RestClientException;
    import org.springframework.web.client.RestTemplate;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.nio.charset.StandardCharsets;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    public class RestTemplateUtils {
    
    
        /**
         *  http 请求 GET
         * @param url 地址
         * @param params 参数
         * @param connecTimeout 连接时间
         * @param readTimeout 读取时间
         * @param retryCount 重试机制
         * @return String 类型
         */
        public static String getHttp(String url, JSONObject params,int connecTimeout,int readTimeout ,int retryCount) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(connecTimeout);
            requestFactory.setReadTimeout(readTimeout);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理
            url = expandURL(url, params.keySet());
            String result = null; // 返回值类型;
            for (int i = 1; i <= retryCount; i++){
                try {
                    result = restTemplate.getForObject(url, String.class, params);
                    return result;
                } catch (RestClientException e) {
                    System.out.println("-----------开始-----------重试count: "+i);
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         *  https 请求 GET
         * @param url 地址
         * @param params 参数
         * @param connecTimeout 连接时间
         * @param readTimeout 读取时间
         * @param retryCount 重试机制
         * @return String 类型
         */
        public static String getHttps(String url, JSONObject params,int connecTimeout,int readTimeout ,int retryCount) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(connecTimeout);
            requestFactory.setReadTimeout(readTimeout);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); //error处理
            restTemplate.setRequestFactory(new HttpsClientRequestFactory()); // 绕过https
            url = expandURL(url, params.keySet());
            String result = null; // 返回值类型;
            for (int i = 1; i <= retryCount; i++){
                try {
                    result = restTemplate.getForObject(url, String.class, params);
                    return result;
                } catch (RestClientException e) {
                    System.out.println("-----------开始-----------重试count: "+i);
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         *  http 请求 post
         * @param url 地址
         * @param params 参数
         * @param headersMap header
         * @param connecTimeout 连接时间
         * @param readTimeout 读取时间
         * @param retryCount 重试机制
         * @return String 类型
         */
        public static String postHttp(String url, JSONObject params, Map headersMap,int connecTimeout,int readTimeout,int retryCount) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
            requestFactory.setConnectTimeout(connecTimeout);
            requestFactory.setReadTimeout(readTimeout);
            //内部实际实现为 HttpClient
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
            // 设置·header信息
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAll(headersMap);
            HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, requestHeaders); // josn utf-8 格式
            String result = null; // 返回值类型;
            for (int i = 1; i <= retryCount; i++){
                try {
                    result = restTemplate.postForObject(url, requestEntity, String.class);
                    return result;
                } catch (RestClientException e) {
                    System.out.println("-----------开始-----------重试count: "+i);
                    e.printStackTrace();
                }
            }
            return result;
        }
    
    
    
        /**
         * 加密参数类型请求  application/x-www-form-urlencoded
         *  MultiValueMap<String, Object>
         * 采用 HttpEntity<MultiValueMap<String, Object>> 构造
         *  http 请求 post
         * @param url 地址
         * @param
         * @param headersMap header
         * @param connecTimeout 连接时间
         * @param readTimeout 读取时间
         * @param retryCount 重试机制
         * @return String 类型
         */
        public static String postHttpEncryption(String url, MultiValueMap<String, Object> postParameters, Map headersMap, int connecTimeout, int readTimeout, int retryCount) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
            requestFactory.setConnectTimeout(connecTimeout);
            requestFactory.setReadTimeout(readTimeout);
            //内部实际实现为 HttpClient
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
            // 设置·header信息
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAll(headersMap);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(postParameters, requestHeaders);
            String result = null; // 返回值类型;
            for (int i = 1; i <= retryCount; i++){
                try {
                    result  = restTemplate.postForObject(url, requestEntity, String.class);
                    return result;
                } catch (RestClientException e) {
                    System.out.println("-----------开始-----------重试count: "+i);
                    e.printStackTrace();
                }
            }
            return result;
        }
    
    
    
    
        /**
         * @param url 请求地址
         * @param params 请求 josn 格式参数
         * @param headersMap headers 头部需要参数
         * @param retryCount 重试机制
         * @return 返回string类型返回值
         * 参数json方法传递
         */
        public static String postHttps(String url, JSONObject params, Map headersMap,int connecTimeout,int readTimeout,int retryCount) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
            requestFactory.setConnectTimeout(connecTimeout);
            requestFactory.setReadTimeout(readTimeout);
            //内部实际实现为 HttpClient
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
            restTemplate.setRequestFactory(new HttpsClientRequestFactory()); // 绕过https
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
            // 设置·header信息
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAll(headersMap);
            HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, requestHeaders); // josn utf-8 格式
            String result = null; // 返回值类型;
            for (int i = 1; i <= retryCount; i++){
                try {
                    result = restTemplate.postForObject(url, requestEntity, String.class);
                    return result;
                } catch (RestClientException e) {
                    System.out.println("-----------开始-----------重试count: "+i);
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * http 请求 post
         *
         * @param url           地址
         * @param params        参数
         * @param headersMap    header
         * @param connecTimeout 连接时间
         * @param readTimeout   读取时间
         * @param retryCount    重试机制
         * @return String 类型
         * 参数是以普通的post参数传递,非json传递参数
         */
        public static String commonPostHttp(String url, Map params, Map headersMap, int connecTimeout, int readTimeout, int retryCount) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
            requestFactory.setConnectTimeout(connecTimeout);
            requestFactory.setReadTimeout(readTimeout);
            //内部实际实现为 HttpClient
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
            // 设置·header信息
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAll(headersMap);
    
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(params, requestHeaders); // josn utf-8 格式
            String result = null; // 返回值类型;
            for (int i = 1; i <= retryCount; i++) {
                try {
                    result = restTemplate.postForObject(url, requestEntity, String.class);
                    return result;
                } catch (RestClientException e) {
                    log.error("-----------开始-----------重试count: " + i);
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        private static MultiValueMap<String, String> createMultiValueMap(JSONObject params) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            for (String key : params.keySet()) {
                if (params.get(key) instanceof List) {
                    for (Iterator<String> it = ((List<String>) params.get(key)).iterator(); it.hasNext(); ) {
                        String value = it.next();
                        map.add(key, value);
                    }
                } else {
                    map.add(key, params.getString(key));
                }
            }
            return map;
        }
    
        /**
         * @param url
         * @param keys
         * @return
         * @Title: expandURL
         * @author:
         * @Description: TODO
         * @return: String
         */
        private static String expandURL(String url, Set<?> keys) {
            final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
            Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
            StringBuilder sb = new StringBuilder(url);
            if (mc.find()) {
                sb.append("&");
            } else {
                sb.append("?");
            }
    
            for (Object key : keys) {
                sb.append(key).append("=").append("{").append(key).append("}").append("&");
            }
            return sb.deleteCharAt(sb.length() - 1).toString();
        }
    
    
        /**
         * @ClassName: DefaultResponseErrorHandler
         * @Description: TODO
         * @author:
         * @date: 2
         */
        private static class DefaultResponseErrorHandler implements ResponseErrorHandler {
    
            /** 对response进行判断,如果是异常情况,返回true */
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getStatusCode().value() != HttpServletResponse.SC_OK;
            }
    
            /** 异常情况时的处理方法 */
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
                StringBuilder sb = new StringBuilder();
                String str = null;
                while ((str = br.readLine()) != null) {
                    sb.append(str);
                }
                try {
                    throw new Exception(sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    

    绕过Https 工具类

    import org.springframework.http.client.SimpleClientHttpRequestFactory;
    
    import javax.net.ssl.*;
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.security.cert.X509Certificate;
    
    /**
     * Https 绕过
     */
    public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    
    
        @Override
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
            try {
                if (!(connection instanceof HttpsURLConnection)) {
                    throw new RuntimeException("An instance of HttpsURLConnection is expected");
                }
    
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    
                TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            @Override
                            public X509Certificate[] getAcceptedIssuers() {
                                return null;
                            }
                            @Override
                            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                            }
                            @Override
                            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                            }
    
                        }
                };
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
    
                httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
    
                super.prepareConnection(httpsConnection, httpMethod);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
         * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
         */
        // SSLSocketFactory用于创建 SSLSockets
        private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
    
            private final SSLSocketFactory delegate;
    
            public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
                this.delegate = delegate;
            }
    
            // 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
            // 这些默认的服务的最低质量要求保密保护和服务器身份验证
            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }
    
            // 返回的密码套件可用于SSL连接启用的名字
            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
    
    
            @Override
            public Socket createSocket(final Socket socket, final String host, final int port,
                                       final boolean autoClose) throws IOException {
                final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
                return overrideProtocol(underlyingSocket);
            }
    
    
            @Override
            public Socket createSocket(final String host, final int port) throws IOException {
                final Socket underlyingSocket = delegate.createSocket(host, port);
                return overrideProtocol(underlyingSocket);
            }
    
            @Override
            public Socket createSocket(final String host, final int port, final InetAddress localAddress,
                                       final int localPort) throws
                    IOException {
                final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
                return overrideProtocol(underlyingSocket);
            }
    
            @Override
            public Socket createSocket(final InetAddress host, final int port) throws IOException {
                final Socket underlyingSocket = delegate.createSocket(host, port);
                return overrideProtocol(underlyingSocket);
            }
    
            @Override
            public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
                                       final int localPort) throws
                    IOException {
                final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
                return overrideProtocol(underlyingSocket);
            }
    
            private Socket overrideProtocol(final Socket socket) {
                if (!(socket instanceof SSLSocket)) {
                    throw new RuntimeException("An instance of SSLSocket is expected");
                }
                ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
                return socket;
            }
        }
    }
    
    
  • 相关阅读:
    [算法]全排列类问题
    windows下python安装Numpy和Scipy模块
    EMC校招笔试题目
    word2012写论文之参考文献和图片
    我的MBTI性格测试
    单例模式三境界
    css3滤镜Filter使用
    利用nginx 虚拟主机、请求转发实现不同端口web访问
    使用gitbook 发布一个教程文档网站
    linux 下CentOS 下 npm命令安装gitbook失败的问题
  • 原文地址:https://www.cnblogs.com/TimeSay/p/11751212.html
Copyright © 2020-2023  润新知