[英]How to use SSL Client certificate with Apache commons http client
[英]Apache Http Client SSL certificate error
我知道之前有人問過它,但我嘗試了我找到的所有解決方案,但仍然無法正常工作。
基本上,我試圖通過 Apache Http Client (4.3) 獲取一些內容,而我連接的網站存在一些 SSL 問題。
首先,我收到了SSLException
和unrecognized_name
消息。 我試圖通過將jsse.enableSNIExtension
屬性設置為false
來解決這個問題。
然后,我得到了這個異常: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
然后我嘗試提供我贏得的SSLFactory
來接受所有證書,但我仍然遇到相同的異常。 這是我的代碼:
private static void sslTest() throws Exception {
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.useTLS()
.build();
SSLConnectionSocketFactory connectionFactory =
new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(connectionFactory)
.setDefaultCookieStore(cookieStore)
.build();
URI uri = new URIBuilder()
.setScheme("https")
.setHost(BASE_URL)
.build();
String responseBody = httpclient.execute(new HttpGet(uri), RESPONSE_HANDLER);
}
非常感謝所有幫助!
另請注意,信任自簽名證書並不意味着信任任何任意證書。
嘗試以這種方式設置 SSL 上下文:
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null,
new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
return true;
}
})
.useTLS()
.build();
另請注意,通常不加選擇地信任證書首先違背了使用 SSL 的目的。 在絕對必要或僅用於測試時使用
在 Http 客戶端 4.5.2 中:
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null,
new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf;
sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
進而:
HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslsf);
您的信任庫不信任服務器證書。
允許所有主機名是HTTPS一步,如果該證書是可信的,只能被調用。
以下是讓 Apache 4x 信任一切
static {
// avoid error javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
System.setProperty("jsse.enableSNIExtension", "false");
}
public static HttpClientBuilder createTrustAllHttpClientBuilder() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, (chain, authType) -> true);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(sslsf);
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException(e);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.