使用 Apache HttpClient 处理无效的 SSL 证书
问题:
使用 Apache HttpClient 时建立 HTTPS 连接时,遇到与无效 SSL 证书相关的错误。如何克服这些错误,同时避免使用 KeyManager 和 TrustManager?
答案:
在 Apache HttpClient 中处理无效的 SSL 证书需要以下方法之一:
为任何证书实现 TrustManager:
以下代码演示了如何使用接受任何证书的 TrustManager 创建 SSLContext:
<code class="java">import java.net.URL; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class SSLTest { public static void main(String [] args) throws Exception { // configure the SSLContext with a TrustManager SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom()); SSLContext.setDefault(ctx); URL url = new URL("https://mms.nw.ru"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); System.out.println(conn.getResponseCode()); conn.disconnect(); } private static class DefaultTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }</code>
以上是如何在没有 KeyManager 和 TrustManager 的情况下处理 Apache HttpClient 中无效的 SSL 证书?的详细内容。更多信息请关注PHP中文网其他相关文章!