避免经常更换证书,或者证书过期问题,在老项目中使用   可以参考: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:

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.HashMap;
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.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  ");
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-type", "application/json");
        return post(url, message, headers);
    }
    
    
    
    /**
     * @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 postForm(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 {}", url, headers);
        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);
    }
    
    
    
    /**
     * https 绕过证书
     * @param url
     * @param message json
     * @return
     */
    public static JSONObject postxml(String url, String message) {
        log.info("enter into HttpUtils class postjson method  ");
        HashMap<String, String> headers = new HashMap<>();
//        headers.put("Content-type", "application/soap+xml;charset=UTF-8");
        headers.put("Content-type", "application/xml;charset=UTF-8");
        return post(url, message, headers);
    }


    
 
    /**
     * @param url
     * @param headers
     * @return
     */
    public static JSONObject get(String url,Map<String, String> headers){
      return get(url,null,headers);
    }
    
    /**
     * @param url
     * @param paramMap
     * @param headers
     * @return
     */
    public static JSONObject get(String url, Map<String, String> paramMap,Map<String, String> headers){
        HttpGet httpGet = new HttpGet();
        
        if(paramMap!=null) {
             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));
        }else
        {
            httpGet.setURI(URI.create(url));
        }
        // set herder
         if (headers != null) {
             for (Entry<String, String> entry : headers.entrySet()) {
                 httpGet.addHeader(entry.getKey(), entry.getValue());
             }
         }
        return sendRequest(httpGet);
    }
    
    
    
    
    /**
     * @param url
     * @param message  json or xml
     * @param headers
     * @return
     */
    public static JSONObject post(String url, String message,Map<String, String> headers) {
        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");
            //add header
            headers.forEach((key,value)->{
                httpPost.setHeader(key,value);
            });
            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();
            }
        }
    }
    
    

    /**
     * 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(300000).setConnectTimeout(300000)
                    .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()");
        }
    }
    
    
}

 

posted on 2019-06-28 15:26  lshan  阅读(1550)  评论(0编辑  收藏  举报