HttpClient 中自定义SSL

当下面两种情况的SSL,用HttpClient建立连接时,需要使用自定义SSL:

 

  • Ability to accept self-signed or untrusted SSL certificates. This is highlighted by an SSLException with the message Unrecognized SSL handshake (or similar) being thrown when a connection attempt is made.
  • You want to use a third party SSL library instead of Sun's default implementation.

常见代码如下:

 

PostMethod post = new PostMethod(masupServiceURL);
Protocol myhttps = new Protocol("https",
                new MySecureProtocolSocketFactory(), 443);

Protocol.registerProtocol("https", myhttps);

HttpClient client = new HttpClient();

 

上面的代码中MySecureProtocolSocketFactory的作用就是当SSL证书不受信任(如证书过期),HttpClient可以自动接受证书。当然这种用法有一定的安全隐患,因此当使用这种方法时,还是得先考虑需求。

你可能感兴趣的:(sun)