场景: 解决PKIX:unable to find valid certification path to requested target 的问题
- Open Feign
@Configurationpublic class WebConfig {@Bean@ConditionalOnMissingBeanpublic Client feignClient() throws NoSuchAlgorithmException, KeyManagementException {SSLContext ctx = SSLContext.getInstance("SSL");X509TrustManager tm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};ctx.init(null, new TrustManager[]{tm}, null);return new Client.Default(ctx.getSocketFactory(),new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {// TODO Auto-generated method stubreturn true;}});}}
Feign使用示例
JsypxRequest request = Feign.builder().encoder(new GsonEncoder()).decoder(new GsonDecoder()).client(client).target(BaiduRequest.class, "https://www.baidu.com");
- RestTemplate
public static RestTemplate getInstance(Proxy proxy, int connTimeout, int readTimeout, boolean enableSslCheck) {final RestTemplate restTemplate = new RestTemplate();// sslIgnoreSimpleClientHttpRequestFactory requestFactory;if (!enableSslCheck) {requestFactory = getUnsafeClientHttpRequestFactory();} else {requestFactory = new SimpleClientHttpRequestFactory();}// proxyif (proxy != null)requestFactory.setProxy(proxy);// timeoutrequestFactory.setConnectTimeout(connTimeout);requestFactory.setReadTimeout(readTimeout);restTemplate.setRequestFactory(requestFactory);return restTemplate;}private 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() {@Overrideprotected void prepareConnection(HttpURLConnection connection,@NotNull String httpMethod) throws IOException {super.prepareConnection(connection, httpMethod);if (connection instanceof HttpsURLConnection) {((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());}}};}public static RestTemplate getInstance(Proxy proxy, boolean enableSsLCheck) {return getInstance(proxy, -1, -1, enableSsLCheck);}
RestTemplate 使用示例
restTemplate = getInstance(null ,false);
restTemplate.exchange.....