Bootstrap

https证书集成到java中

一、说明

        项目中经常会遇到业务系统使用https的情况,对方会提供jks或pem证书,此时我方有3种方式处理,1种是忽略证书的校验(比较常见的做法,因为有时候证书现在大多数是绑定要域名而不是ip上,此时如果使用的jdk1.8(jdk1.6不会有问题)用ip访问就会报错:java.security.cert.CertificateException: No subject alternative names present)),第二种是将证书导入到jre中,第三种就是代码上指定jks

二、示例

2.1方式1:忽略证书

      在获取HttpClient的时候,要使用忽略证书处理过的HttpClient

/***
 * 忽略证书
 */
public static CloseableHttpClient createHttpClient(String url){
    try {
        if(url.startsWith("http://")){
            return HttpClients.createDefault();
        }
        X509TrustManager x509mgr = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) {
            }
            public void checkServerTrusted(X509Certificate[] xcs, String string) {
            }
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        SSLContext sslContext = null;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { x509mgr }, 
;