我正在做一个https帖子,但是却得到ssl异常的一个例外,不受信任的服务器证书。如果我做正常的HTTP,它工作正常。我是否必须以某种方式接受服务器证书?
我正在猜测,但是如果你想进行实际的握手,则必须让android知道你的证书。如果你只想接受任何内容,请使用以下伪代码通过Apache HTTP Client获得所需的内容:
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的类,但实际上没有任何方法可以执行任何工作,请在此处获取示例。
祝好运!
这就是我在做什么。它只是不再检查证书了。
// 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(); }