项目中需要连接SSL服务器,但是不需要客户端安装任何证书,也不校验任何服务器证书的正确与否。代码如下:

protected ConnectionSocketFactory createDefaultSecureSocketFactory() 

{

try {

SSLContext ctx = SSLContext.getInstance("SSL");

X509TrustManager tm = new X509TrustManager() {  

public X509Certificate[] getAcceptedIssuers() {

return null;

}

public void checkServerTrusted(X509Certificate[] certs, String authType)

throws CertificateException {

return;

}

public void checkClientTrusted(X509Certificate[] certs, String authType)

throws CertificateException {

return;

       };  

ctx.init(null, new TrustManager[] { tm }, null);

final SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

       return ssf;

} catch (NoSuchAlgorithmException e) {

DCALogManager.Error("SSL Connection Failure!",10003,e);

} catch (KeyManagementException e) {

DCALogManager.Error("SSL Connection Failure!",10003,e);

}  

  return SSLConnectionSocketFactory.getSocketFactory();

}

其实httpClient中的SSLConnectionSocketFactory是专门管理SSL的工程类,仔细研读一下就可以名表其中的大部分原理。