以下是 JDK 1.5以上、 Apache Common HttpClient 3.1 的做法。
private HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String arg1)
throws java.security.cert.CertificateException {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String arg1)
throws java.security.cert.CertificateException {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier verifier = new X509HostnameVerifier() {
public void verify(String string, SSLSocket ssls)
throws IOException {
}
public void verify(String string, String[] strings,
String[] strings1) throws SSLException {
}
public boolean verify(String string, SSLSession ssls) {
return true;
}
public void verify(String arg0,
java.security.cert.X509Certificate arg1)
throws SSLException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(verifier);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient = (DefaultHttpClient) this.wrapClient(httpclient);
使用 wrap 過的 HttpClilent 就可以囉~
沒有留言:
張貼留言