https HttpUtils 绕过证书

避免经常更换证书,或者证书过期问题,在老项目中使用   可以参考:https://www.programcreek.com/java-api-examples/index.php?api=org.apache.http.conn.ssl.SSLConnectionSocketFactory

依赖:

  <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

HttpUtils:

package com.icil.elsa.subscribe.milestone.common.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import net.bytebuddy.asm.Advice.This;
/**
 * *************************************************************************
 * <PRE>
 *  @ClassName:    : HttpUtils 
 *
 *  @Description:    : 绕过 https 证书
 *
 *  @Creation Date   : 16 Aug 2018 2:20:44 PM
 *
 *  @Author          :  Sea
 *  
 *
 * </PRE>
 **************************************************************************
 */
public class HttpUtils {
    
    private static final  Logger  log=LoggerFactory.getLogger(This.class);
    public static final  String  HTTPSTATUS="status";
    public static final  String  HTTPRESPONSE="response";
    /**
     * https 绕过证书
     * 
     * @param url
     * @param message json
     * @return
     * @return
     */
    public static JSONObject postjson(String url, String message) {
        log.info("enter into HttpUtils class postjson method  ");
        log.info("url is :{} ",url);
        JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        CloseableHttpClient httpClient = null; // 创建默认的httpClient实例
        X509TrustManager xtm = new X509TrustManager() { // 创建TrustManager
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        try {
            // TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("SSL");
            // 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[] { xtm }, null);
            // 创建SSLSocketFactory
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx); // SSLConnectionSocketFactory
            // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
            RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
            schemeRegistry.register("https", socketFactory);
            schemeRegistry.register("http", new PlainConnectionSocketFactory());
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                    schemeRegistry.build());
            httpClient = HttpClients.custom().setConnectionManager(connManager).build();
            // 创建HttpPost
            HttpPost httpPost = new HttpPost(url);
            StringEntity requestEntity = new StringEntity(message, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            // 设置连接时间,与超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(5000)
                    .build();
            httpPost.setConfig(requestConfig);
            // 执行请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // 读取内容
            HttpEntity entity = httpResponse.getEntity(); // 获取响应实体
            String result = "";
            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            jsonObject.put(HTTPSTATUS, httpResponse.getStatusLine().getStatusCode());
            jsonObject.put(HTTPRESPONSE, result);
            return jsonObject;
        } catch (Exception e) 
        {
             log.error("send http request failed, exception is {}", e);
             jsonObject.put(HTTPSTATUS, 500);
             jsonObject.put(HTTPRESPONSE, e);
             return jsonObject;
        } finally {
            // 释放连接
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    
    /**
     * @param url
     * @return
     */
    public static JSONObject get(String url)  {
        HttpGet httpGet = new HttpGet();
        httpGet.setURI(URI.create(url));
        return sendRequest(httpGet);
    }

    
    /**
     * 封装HTTP GET方法
     * 有参数的Get请求
     * @param
     * @param
     * @return
     * @throws ClientProtocolException
     * @throws java.io.IOException
     */
    public static JSONObject get(String url, Map<String, String> paramMap){
        HttpGet httpGet = new HttpGet();
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        //add parameters
        for (Map.Entry<String, String> entry : set) 
        {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        httpGet.setURI(URI.create(url + "?" + param));
        return sendRequest(httpGet);
    }
    


    /**
     * @param url
     * @param headers  headers.put("Content-Type", "application/x-www-form-urlencoded");
     * @param paramMap  类似表单请求
     * @return :{"status":200,"response":"{"success":false,"errorCode":"failure","errorMsg":"回传接口没有点击开始回传"}"}
     * @throws IOException
     */
    public static JSONObject postParams(String url, Map<String, String> headers, Map<String, String> paramMap) {
        log.info("Enter into httpUtil.postWithParam() method ");
        log.info("send request ,the url is {},,header is {},paramMap is {}", url, headers, paramMap);
        HttpPost post = new HttpPost(url);
        // add request parameters
        if (paramMap != null && !paramMap.isEmpty()) {
            List<NameValuePair> list = new ArrayList<>();
            Iterator<Entry<String, String>> iterator = paramMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            // set chart encode
            if (!list.isEmpty()) {
                try {
                    post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    log.error("UrlEncodedFormEntity  exception : {}", e);
                }
            }
        }
        // set herder
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }
        log.info("end of httpUtil.postWithParam() method ");
        return sendRequest(post);
    }
    
    

    /**
     * send request
     * @param request
     * @return
     */
    public static JSONObject sendRequest(HttpRequestBase request) {
        JSONObject jsonObject = new JSONObject();
        CloseableHttpClient httpClient = null;
        // 创建TrustManager
        X509TrustManager xtm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        try {
            // 设置连接时间,与超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(5000)
                    .build();
            request.setConfig(requestConfig);
            // TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("SSL");
            // 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[] { xtm }, null);
            // 创建SSLSocketFactory
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx); // SSLConnectionSocketFactory
            // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
            RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
            schemeRegistry.register("https", socketFactory);
            schemeRegistry.register("http", new PlainConnectionSocketFactory());
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
            httpClient = HttpClients.custom().setConnectionManager(connManager).build();
            CloseableHttpResponse httpResponse = httpClient.execute(request);
            // set response char encode
            String response = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            jsonObject.put(HTTPSTATUS, httpResponse.getStatusLine().getStatusCode());
            jsonObject.put(HTTPRESPONSE, response);
            return jsonObject;
        } catch (Exception e) {
            log.error("send http request failed, exception is {}", e);
            jsonObject.put(HTTPSTATUS, 500);
            jsonObject.put(HTTPRESPONSE, e);
            return jsonObject;
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("close http client failed, exception is {}", e);
            }
            log.info("end of httpUtil.sendRequest()");
        }
    }
    
    
}

HttpUtils: 方法已过时

/**
     * https 绕过证书
     * @param url
     * @param message
     * @return 
     * @return
     */
    public static String spost(String  url,String message) {
        String result=null;
        DefaultHttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例 
        X509TrustManager xtm = new X509TrustManager()
        { //创建TrustManager 
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
        public X509Certificate[] getAcceptedIssuers() { return null; } 
        }; 
        try { 
        //TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext 
        SSLContext ctx = SSLContext.getInstance("SSL"); 
        //使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用 
        ctx.init(null, new TrustManager[]{xtm}, null); 
        //创建SSLSocketFactory 
        @SuppressWarnings("deprecation")
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); //SSLConnectionSocketFactory
        //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上 
        httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443)); 
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        //创建Httppost方法的实例 
        HttpPost httpPost = new HttpPost(url); //创建HttpPost 
        StringEntity requestEntity = new StringEntity(message, "utf-8");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(requestEntity);
        //设置连接时间,与超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(5000).build();
        httpPost.setConfig(requestConfig);
        HttpResponse response = httpClient.execute(httpPost); 
        //执行 
        if(response.getStatusLine().getStatusCode() == 200) 
        { 
          //读取内容 
          HttpEntity entity = response.getEntity(); //获取响应实体 
          if (null != entity) 
          {
              result = EntityUtils.toString(entity, "UTF-8");
          }
        } else
          log.error("获取temp_id时,认证平台发生内部错误!!");
        }catch(Exception e){
          log.error("认证失败,原因:[认证系统异常] exception is ",e);
        }finally{ 
          //释放连接 
          httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源 
        }
        return result;
    }
    

原文地址:https://www.cnblogs.com/lshan/p/11102897.html