HTPPS请求 证书 解决方案

来源:互联网 发布:java websocket client 编辑:程序博客网 时间:2024/06/06 06:43

1.忽略证书

    public static String sendGetByProxy(String url, String param, String encode,String host,int port) throws Exception {        String result = "";        BufferedReader in = null;        String urlNameString = url + "?" + param;        URL realUrl = new URL(urlNameString);        if("https".equalsIgnoreCase(realUrl.getProtocol())){            SslUtils.ignoreSsl();        }        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));          URLConnection connection = (URLConnection) realUrl.openConnection(proxy);        // 设置通用的请求属性        connection.setRequestProperty("accept", "*/*");        connection.setRequestProperty("connection", "Keep-Alive");        connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");        connection.setConnectTimeout(3000);        connection.setReadTimeout(3000);        // 建立实际的连接        connection.connect();        in = new BufferedReader(new InputStreamReader(                connection.getInputStream(),encode));        String line;        while ((line = in.readLine()) != null) {            result += line;        }        try {            if (in != null) {                in.close();            }        } catch (Exception e2) {            e2.printStackTrace();        }        return result;    }
import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;public class SslUtils {    private static void trustAllHttpsCertificates() throws Exception {        TrustManager[] trustAllCerts = new TrustManager[1];        TrustManager tm = new miTM();        trustAllCerts[0] = tm;        SSLContext sc = SSLContext.getInstance("SSL");        sc.init(null, trustAllCerts, null);        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());    }    static class miTM implements TrustManager,X509TrustManager {        public X509Certificate[] getAcceptedIssuers() {            return null;        }        public boolean isServerTrusted(X509Certificate[] certs) {            return true;        }        public boolean isClientTrusted(X509Certificate[] certs) {            return true;        }        public void checkServerTrusted(X509Certificate[] certs, String authType)                throws CertificateException {            return;        }        public void checkClientTrusted(X509Certificate[] certs, String authType)                throws CertificateException {            return;        }    }    /**     * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用     * @throws Exception     */    public static void ignoreSsl() throws Exception{        HostnameVerifier hv = new HostnameVerifier() {            public boolean verify(String urlHostName, SSLSession session) {                System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());                return true;            }        };        trustAllHttpsCertificates();        HttpsURLConnection.setDefaultHostnameVerifier(hv);    }}

2.安装证书

2.1 代码

    public static void main(String[] args) throws Exception {        String host = "";        int port = 8888;        // 创建SSLContext对象,并使用我们指定的信任管理器初始化         TrustManager[] tm = { new MyX509TrustManager() };         SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");         sslContext.init(null, tm, new java.security.SecureRandom());         // 从上述SSLContext对象中得到SSLSocketFactory对象         SSLSocketFactory ssf = sslContext.getSocketFactory();         // 创建URL对象         URL myURL = new URL("");         // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象         Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));         HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection(proxy);         httpsConn.setSSLSocketFactory(ssf);         // 取得该连接的输入流,以读取响应内容         InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());         // 读取服务器的响应内容并显示         int respInt = insr.read();         while (respInt != -1) {             System.out.print((char) respInt);             respInt = insr.read();         } 
import java.io.FileInputStream; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager;import com.jfinal.kit.PathKit; public class MyX509TrustManager implements X509TrustManager {     /*      * The default X509TrustManager returned by SunX509.  We'll delegate      * decisions to it, and fall back to the logic in this class if the      * default X509TrustManager doesn't trust it.      */     X509TrustManager sunJSSEX509TrustManager;     MyX509TrustManager() throws Exception {         // create a "default" JSSE X509TrustManager.         KeyStore ks = KeyStore.getInstance("JKS");         ks.load(new FileInputStream(PathKit.getWebRootPath()+"/media/static/swzj.jks"),             "987321".toCharArray());         TrustManagerFactory tmf =         TrustManagerFactory.getInstance("SunX509", "SunJSSE");         tmf.init(ks);         TrustManager tms [] = tmf.getTrustManagers();         /*          * Iterate over the returned trustmanagers, look          * for an instance of X509TrustManager.  If found,          * use that as our "default" trust manager.          */         for (int i = 0; i < tms.length; i++) {             if (tms[i] instanceof X509TrustManager) {                 sunJSSEX509TrustManager = (X509TrustManager) tms[i];                 return;             }         }         /*          * Find some other way to initialize, or else we have to fail the          * constructor.          */         throw new Exception("Couldn't initialize");     }     /*      * Delegate to the default trust manager.      */     public void checkClientTrusted(X509Certificate[] chain, String authType)                 throws CertificateException {         try {             sunJSSEX509TrustManager.checkClientTrusted(chain, authType);         } catch (CertificateException excep) {             // do any special handling here, or rethrow exception.         }     }     /*      * Delegate to the default trust manager.      */     public void checkServerTrusted(X509Certificate[] chain, String authType)                 throws CertificateException {         try {             sunJSSEX509TrustManager.checkServerTrusted(chain, authType);         } catch (CertificateException excep) {             /*              * Possibly pop up a dialog box asking whether to trust the              * cert chain.              */         }     }     /*      * Merely pass this through.      */     public X509Certificate[] getAcceptedIssuers() {         return sunJSSEX509TrustManager.getAcceptedIssuers();     } } 

2.2 证书导入jks文件

实例:P7B格式证书(证书链)导入jks文件
2.2.1 安装证书

2.2.2 导出cer格式,p7b证书,包含根证书和子证书。分别导出为 根rootca.cer和子rootcaserver.cer。

这里写图片描述

2.2.3 使用java keytool工具(jdk bin目录) 将证书 分别导入 jks文件,遇到是否信任该证书提示时,输入y。(keytool无法直接导入p7b文件)

是否信任此证书? []:  y证书已添加到密钥库中C:\Program Files\Java\jdk1.7.0_80\bin>keytool -import -alias rootcaserver -trustcacerts -file d:/rootcaserver.cer -keystore d:/test.jks输入密钥库口令:证书已添加到密钥库中C:\Program Files\Java\jdk1.7.0_80\bin>keytool -import -alias rootcaserver -trustcacerts -file d:/rootcaserver.cer -keystore d:/test.jks
1 0