關於 https 信任例外問題

1 篇文章 / 0 new
author
關於 https 信任例外問題
當 Server 端啟用 SSL(https), 且簽章沒有經過第三方公開認證(要錢), 使用 http 連接時就會出現 exception, 這時就用下列方式進行
► 建立信任網站登錄來進行連線
public DefaultHttpClient getClient() {
        DefaultHttpClient ret = null;
        //sets up parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);
        //registers schemes for both http and https
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, 443));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        ret = new DefaultHttpClient(manager, params);
        return ret;
    }
► 取消驗證/全部信任
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[] {};
    }
    @Override
    public void checkClientTrusted( X509Certificate[] chain, String authType) throws CertificateException { }
    @Override
    public void checkServerTrusted( X509Certificate[] chain, String authType) throws CertificateException { }
} };
// 加入全部信任
try {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) { }
String result = "";
try {
    URL uurl;
    uurl = new URL("https://127.0.0.1:8080/hlist");
    HttpsURLConnection conn = (HttpsURLConnection) uurl.openConnection();
    conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    InputStream inputStream = conn.getInputStream();                            
    if (inputStream != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[20];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(inputStream));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            inputStream.close();
        }
        result = writer.toString();
    }
} catch (Exception e) { }

from http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-exa... , http://stackoverflow.com/questions/6825226/trust-anchor-not-found-for-an...
Free Web Hosting