我在Stackoverflow上看到了很多toppics,而且整个网络都在尝试做同样的事情:
接受SSL证书.但是,这些答案似乎都不适用于我的问题,因为我没有弄乱HTTPSUrlConnections.
如果我正在请求代码通常看起来像这样(注释清除):
//creates an HTTP-Post with an URL HttpPost post = createBaseHttpPost(); //loads the request Data inside the httpPost post.setEntity(getHttpPostEntity()); //appends some Headers like user-agend or Request UUIDs appendHeaders(post); HttpClient client = new DefaultHttpClient(); //mResponse is a custom Object which is returned //from the custom ResponseHandler(mResponseHandler) mResponse = client.execute(post,mResponseHandler); return mResponse;
我读到我应该注入自己的TrustManager和X509HostnameVerivier.我创建了这样的:
private static final TrustManager[] TRUST_ALL_CERTS = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException { } public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException { } } }; private static X509HostnameVerifier ACCEPT_ALL_HOSTNAMES = new X509HostnameVerifier() { public void verify(String host,String[] cns,String[] subjectAlts) throws SSLException { } public void verify(String host,X509Certificate cert) throws SSLException { } public void verify(String host,SSLSocket ssl) throws IOException { } public boolean verify(String host,SSLSession session) { return true; } };
如果我在我的请求中注入HostnameVerifier像这样(客户端是上面的DefaultHttpClient)
SSLSocketFactory ssl = (SSLSocketFactory)client.getConnectionManager().getSchemeRegistry().getScheme("https").getSocketFactory(); ssl.setHostnameVerifier(ACCEPT_ALL_HOSTNAMES);
响应从“主机名**不匹配”变为“错误请求”.我想我必须设置TrustManager,但是我无法在我的请求中设置它,因为我没有使用HttpsUrlConnections在我看到它的任何地方.
解决方法
您正在使用HttpClient,因此用于设置信任管理器的API与HttpsURLConnection有所不同,但过程是相同的:
>使用受信任证书(服务器的自签名证书)加载密钥库文件
>用它初始化KeyStore.
>使用2中的KeyStore创建一个SocketFactory.
>设置HTTP客户端库以在创建SSL套接字时使用它.
Android的文档中描述了这一点:http://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory.html
有关该主题的更详细的文章显示了如何创建信任库文件:http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html
一些背景信息和示例代码:http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
这是初始化HttpClient所需的代码:
KeyStore localTrustStore = KeyStore.getInstance("BKS"); InputStream in = getResources().openRawResource(R.raw.mytruststore); localTrustStore.load(in,TRUSTSTORE_PASSWORD.tocharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http",PlainSocketFactory .getSocketFactory(),80)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); schemeRegistry.register(new Scheme("https",sslSocketFactory,443)); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new ThreadSafeClientConnManager(params,schemeRegistry); HttpClient client = new DefaultHttpClient(cm,params);
此时,您没有理由信任所有证书.如果你这样做,那一切都在你身上:)