当前位置: 首页 > 知识库问答 >
问题:

Spring RestTemplate exchange post不使用引发SunCertPathBuilderException的SSL

尹雅健
2023-03-14
 public <T> T getByRestTemplate(String url, Object param, boolean isSSL, String token, ParameterizedTypeReference<T> responseType) throws RestClientException {
        HttpEntity<Object> requestEntity = makeHttpEntity(param, token);
        RestTemplate restTemplate = buildRestTemplate(isSSL);
        ResponseEntity<T> responseEntity;
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, responseType);
        return responseEntity.getBody();
    }

    public <T> T postByRestTemplate(String url, Object param, boolean isSSL, String token, Class<T> responseType) throws RestClientException {
        HttpEntity<Object> requestEntity = makeHttpEntity(param, token);
        RestTemplate restTemplate = prepareRestTemplate(isSSL);
        ResponseEntity<T> responseEntity;
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        return responseEntity.getBody();
    }

   private RestTemplate prepareRestTemplate(boolean isSSL){
        int connectTimeOut = (appConfigProperties.getConnectTimeOut()!=0)?appConfigProperties.getConnectTimeOut():5000;
        int readTimeOut = (appConfigProperties.getReadTimeOut()!=0)?appConfigProperties.getConnectTimeOut():5000;

        RestTemplate restTemplate = buildRestTemplate(isSSL);
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

        requestFactory.setConnectTimeout(connectTimeOut);
        requestFactory.setReadTimeout(readTimeOut);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }

    private RestTemplate buildRestTemplate(boolean isSSL) {
        RestTemplate restTemplate = null;
        if (isSSL) {
            try {
                restTemplate = restTemplateSSL.restTemplateSSL();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            restTemplate = restTemplateBuilder.build();
        }

        return restTemplate;
    }
    private static TrustManager[] createTrustManagers() {
        TrustManager[] trustAllCerts;
        trustAllCerts = new TrustManager[]{new X509ExtendedTrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s){
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) {
            }
        }};
        return trustAllCerts;
    }

 public RestTemplate restTemplateSSL() throws Exception {
        SSLContext sslContext = SSLContext.getInstance(SSL_TLS);
        sslContext.init(null, createTrustManagers(), new java.security.SecureRandom());

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);

        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register(SSL_HTTPS, csf)
                .build();

        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .setConnectionManager(cm)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        return new RestTemplate(requestFactory);
    }

这是我得到的原木。

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target] with root cause

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) ~[na:1.8.0_192]
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) ~[na:1.8.0_192]
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) ~[na:1.8.0_192]
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392) ~[na:1.8.0_192]
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302) ~[na:1.8.0_192]
    at sun.security.validator.Validator.validate(Validator.java:262) ~[na:1.8.0_192]
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) ~[na:1.8.0_192]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) ~[na:1.8.0_192]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) ~[na:1.8.0_192]
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621) ~[na:1.8.0_192]
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223) ~[na:1.8.0_192]
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037) ~[na:1.8.0_192]
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:965) ~[na:1.8.0_192]
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064) ~[na:1.8.0_192]
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367) ~[na:1.8.0_192]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395) ~[na:1.8.0_192]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379) ~[na:1.8.0_192]
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:436) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:374) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83) ~[httpclient-4.5.9.jar:4.5.9]
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56) ~[httpclient-4.5.9.jar:4.5.9]
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]

我读过很多其他的帖子和stackoverflow问答

使用Spring RestTemplate访问Https Rest服务

以及更多关于这个问题的信息。但没有成功。我不知道我还能怎么尝试。

共有1个答案

吴靖
2023-03-14

这毕竟是个愚蠢的错误。

在为POST请求设置restClient时,我犯了一个错误,覆盖了RequestFactory,因此删除了前面的SSL连接设置。

希望没有人犯这种错误!

 类似资料:
  • 问题内容: 我有这样的HTML代码: 我想单击文本为 Home 的链接。由于此Home链接在登录后出现,因此我具有如下代码: 登录之前的部分效果很好。但是最后一行是有问题的 从HTML代码可以看到,它引发了此NoSuchElementException的Home链接。 请问关于我在做什么错的任何指导? 问题答案: 您是否尝试过为此添加隐式等待,以使其等待而不是快速运行。 该调用使浏览器开始轮询,直

  • 我试图从AsyncTask线程中的ObjectMapper获取一个JSON格式的字符串,并且我一直在获取OutOfMemoryError并且在清单文件中已经添加了行 在DoInBackground中执行的AsyncTask方法: Fiscalizacao类: Stacktrace到im存在的问题:

  • 我正在尝试将play-scalr与Play一起使用,并遵循了Github页面上的安装说明,但是当我请求调整大小的映像时,我得到了错误: [RuntimeException:java.lang.UnsupportedClassVersionError:SE/DigiPlant/Scalr/API/Resizer$MODE:不支持Major.Minor版本51.0] 当我编译项目时,JAR是下载的,所

  • 当我使用“Spark Streaming”读取“Kafka”(需要sasl验证),然后将数据存储到“HBase”时,“HBase”给出以下错误 java.io.IOException:java.lang.Reflect.InvocationTargetException在org.apache.hadoop.hbase.client.ConnectionFactor.CreateConnection

  • 问题内容: 假设我们有这样的东西: 问:如何使test_foo3()进行测试,但不会引发MyError?很明显,我可以测试一下: 但我想通过pytest.raises()进行测试。有可能吗?例如:在某种情况下,该函数“ foo”根本没有返回值, 恕我直言,以这种方式进行测试可能很有意义。 问题答案: 如果测试引发任何意外的异常,则测试将失败。您只需调用foo(7),就可以测试没有引发MyError

  • 我正在使用Spring In Action 3 Action学习Spring MVC,我已经实现了显示用户注册表的基本程序,一旦我们提交表单,它将使用进行验证。 这是我的Spring控制器: 这是我的Spitter类文件: 这是我的编辑。显示给用户注册的jsp文件: 要加载表单,我将访问URL为:,一旦表单被加载,我只需提交表单而无需输入任何详细信息,以便我可以检查我的表单是否得到验证。但是我得到