我需要為給定的 url 或 restTemplate 禁用 SSL 知道我可以使用下面的代碼禁用所有 SSL。我怎樣才能只為給定的 URL 制作這個代碼。或者如何為 restTemplate 禁用它。
public class SSLTool {
public static void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {/* intentionally left blank */}
}
}
uj5u.com熱心網友回復:
RestTemplate可以通過以下方式在禁用 SSL 的情況下回傳(您可以根據需要添加其他屬性。):
CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).setSSLHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).build();
HttpComponentsClientHttpRequestFactory req = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate template = new RestTemplate(req);
uj5u.com熱心網友回復:
我用下面的代碼解決了這個問題。這是源鏈接https://stackoverflow.com/a/42689331/16529288
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/480546.html
上一篇:如何為不同的布局重用點擊監聽器
