欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate 和 OpenFeign 忽略HTTPS安全验证写法

程序员文章站 2024-02-14 13:04:28
...

场景: 解决PKIX:unable to find valid certification path to requested target 的问题

  1. Open Feign
	@Configuration
	public class WebConfig {
		@Bean
	    @ConditionalOnMissingBean
	    public Client feignClient() throws NoSuchAlgorithmException, KeyManagementException {
	        SSLContext ctx = SSLContext.getInstance("SSL");
	        X509TrustManager tm = new X509TrustManager() {
	            @Override
	            public void checkClientTrusted(X509Certificate[] chain,
	                    String authType) throws CertificateException {
	            }
	
	            @Override
	            public void checkServerTrusted(X509Certificate[] chain,
	                    String authType) throws CertificateException {
	            }
	
	            @Override
	            public X509Certificate[] getAcceptedIssuers() {
	                return null;
	            }
	        };
	        ctx.init(null, new TrustManager[]{tm}, null);
	        return new Client.Default(ctx.getSocketFactory(),
	                new HostnameVerifier() {
	
	                    @Override
	                    public boolean verify(String hostname, SSLSession session) {
	                        // TODO Auto-generated method stub
	                        return true;
	                    }
	                });
	    }
	}

Feign使用示例

	JsypxRequest request = Feign.builder()
	                .encoder(new GsonEncoder())
	                .decoder(new GsonDecoder())
	                .client(client)
	                .target(BaiduRequest.class, "https://www.baidu.com");
  1. RestTemplate
    public static RestTemplate getInstance(Proxy proxy, int connTimeout, int readTimeout, boolean enableSslCheck) {
        final RestTemplate restTemplate = new RestTemplate();

        // sslIgnore
        SimpleClientHttpRequestFactory requestFactory;
        if (!enableSslCheck) {
            requestFactory = getUnsafeClientHttpRequestFactory();
        } else {
            requestFactory = new SimpleClientHttpRequestFactory();
        }

        // proxy
        if (proxy != null)
            requestFactory.setProxy(proxy);

        // timeout
        requestFactory.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() {
            @Override
            protected 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.....