我正在做一个https帖子,我得到ssl异常的例外不可信服务器证书.如果我做正常的http它工作得很好.我必须以某种方式接受服务器证书吗?
这就是我在做的事情.它根本不再检查证书.
// always verify the host - dont check for certificate final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; /** * Trust every server - dont check for any certificate */ private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection .setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } }
和
HttpURLConnection http = null; if (url.getProtocol().toLowerCase().equals("https")) { trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { http = (HttpURLConnection) url.openConnection(); }
我正在猜测,但如果你想要实际握手,你必须让android知道你的证书.如果您想接受任何内容,那么使用此伪代码来获取Apache HTTP客户端所需的内容:
SchemeRegistry schemeRegistry = new SchemeRegistry (); schemeRegistry.register (new Scheme ("http", PlainSocketFactory.getSocketFactory (), 80)); schemeRegistry.register (new Scheme ("https", new CustomSSLSocketFactory (), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager ( params, schemeRegistry); return new DefaultHttpClient (cm, params);
CustomSSLSocketFactory:
public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory { private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory (); public CustomSSLSocketFactory () { super(null); try { SSLContext context = SSLContext.getInstance ("TLS"); TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () }; context.init (null, tm, new SecureRandom ()); FACTORY = context.getSocketFactory (); } catch (Exception e) { e.printStackTrace(); } } public Socket createSocket() throws IOException { return FACTORY.createSocket(); } // TODO: add other methods like createSocket() and getDefaultCipherSuites(). // Hint: they all just make a call to member FACTORY }
FullX509TrustManager是一个实现javax.net.ssl.X509TrustManager的类,但没有一个方法实际执行任何工作,请在此处获取示例.
祝好运!
在尝试回答这个问题时,我发现了一个更好的教程.有了它,您不必妥协证书检查.
http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html
*我没有写这个,但感谢Bob Lee的工作
您还可以查看我的博客文章,非常类似于crazybobs.
此解决方案也不会影响证书检查,并说明如何在您自己的密钥库中添加可信证书.
http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/