RestTemplate忽略Https证书
实现自定义的SimpleClientHttpRequestFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37private static SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory() {
TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
final SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, byPassTrustManagers, new SecureRandom());
sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
return new SimpleClientHttpRequestFactory() {
protected void prepareConnection(HttpURLConnection connection,
String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setSSLSocketFactory(
sslContext.getSocketFactory());
}
}
};
}在RestTemplate中设置requestFactory
1
2
3RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = getUnsafeClientHttpRequestFactory();
restTemplate.setRequestFactory(requestFactory);
RestTemplate忽略Https证书