Spring中restTemplate忽略https证书的代码实现
spring的restTemplate底层默认是通过httpUrlConnection来实现的http客户端.
1 package myapp.util; 2 3 import org.jetbrains.annotations.NotNull; 4 import org.springframework.http.client.SimpleClientHttpRequestFactory; 5 import org.springframework.web.client.RestTemplate; 6 7 import javax.net.ssl.HttpsURLConnection; 8 import javax.net.ssl.SSLContext; 9 import javax.net.ssl.TrustManager; 10 import javax.net.ssl.X509TrustManager; 11 import java.io.IOException; 12 import java.net.HttpURLConnection; 13 import java.net.Proxy; 14 import java.security.KeyManagementException; 15 import java.security.NoSuchAlgorithmException; 16 import java.security.SecureRandom; 17 import java.security.cert.X509Certificate; 18 19 /** 20 * @author zhangyalong 21 * @version 2019-03-24 19:19 22 */ 23 public class HttpClientUtils { 24 25 public static RestTemplate getInstance(Proxy proxy, int connTimeout, int readTimeout, boolean enableSslCheck) { 26 final RestTemplate restTemplate = new RestTemplate(); 27 28 // sslIgnore 29 SimpleClientHttpRequestFactory requestFactory; 30 if (!enableSslCheck) { 31 requestFactory = getUnsafeClientHttpRequestFactory(); 32 } else { 33 requestFactory = new SimpleClientHttpRequestFactory(); 34 } 35 36 // proxy 37 if (proxy != null) { 38 requestFactory.setProxy(proxy); 39 } 40 41 // timeout 42 requestFactory.setConnectTimeout(connTimeout); 43 requestFactory.setReadTimeout(readTimeout); 44 45 restTemplate.setRequestFactory(requestFactory); 46 return restTemplate; 47 } 48 49 private static SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory() { 50 TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() { 51 52 public X509Certificate[] getAcceptedIssuers() { 53 return new X509Certificate[0]; 54 } 55 56 public void checkClientTrusted(X509Certificate[] chain, String authType) { 57 } 58 59 public void checkServerTrusted(X509Certificate[] chain, String authType) { 60 } 61 }}; 62 final SSLContext sslContext; 63 try { 64 sslContext = SSLContext.getInstance("TLS"); 65 sslContext.init(null, byPassTrustManagers, new SecureRandom()); 66 sslContext.getSocketFactory(); 67 } catch (NoSuchAlgorithmException | KeyManagementException e) { 68 throw new RuntimeException(e); 69 } 70 71 return new SimpleClientHttpRequestFactory() { 72 @Override 73 protected void prepareConnection(HttpURLConnection connection, 74 @NotNull String httpMethod) throws IOException { 75 super.prepareConnection(connection, httpMethod); 76 if (connection instanceof HttpsURLConnection) { 77 ((HttpsURLConnection) connection).setSSLSocketFactory( 78 sslContext.getSocketFactory()); 79 } 80 } 81 }; 82 } 83 84 public static RestTemplate getInstance(Proxy proxy, boolean enableSsLCheck) { 85 return getInstance(proxy, -1, -1, enableSsLCheck); 86 } 87 88 }