首页 > 解决方案 > 我使用spring boot RestTemplate 向公网IP发出json请求,但总是显示断开连接,一分钟后重新连接

问题描述

我使用spring boot RestTemplate 向公网IP发出json请求,但总是显示断开连接,一分钟后重新连接

日志如下:

[] | [20181210 09:11:58.092] | [调试] | [person-certify-7c46cfc9d-t4h7m] | [http-nio-8184-exec-10] | [org.apache.http.wire] | --> http-outgoing-15 << "流结束"| [person-certify-7c46cfc9d-t4h7m] [person-certify]- | [] | [20181210 09:11:58.092] | [调试] | [person-certify-7c46cfc9d-t4h7m] | [http-nio-8184-exec-10] | [oahicDefaultManagedHttpClientConnection] | --> http-outgoing-15: 关闭连接| [person-certify-7c46cfc9d-t4h7m] [person-certify]- | [] | [20181210 09:12:58.092] | [调试] | [person-certify-7c46cfc9d-t4h7m] | [http-nio-8184-exec-10] | [oahicPoolingHttpClientConnectionManager] | --> 连接租用:[id: 17][route: {}-> http://118.25.31.127:80 ][总存活:1;分配的路线:1000 条;总分配:2 of 1000]|

标签: javaspring-boot

解决方案


看起来您的目标服务器只接受 TLSv1.2 连接,您必须确保您的代码只执行与您的代码似乎没有执行的协议的连接。您能否检查您的日志(调试模式)并查看版本?您使用的是什么春季版本?

在调试模式下握手期间应该在日志中显示类似的东西......

.....SSLConnectionSocketFactory - Enabled protocols: [TLSv1]

如何配置 TLSv2 已在此线程中回答How to enforce TLS1.2 to Rest client using Rest Template

总之你可以试试

import javax.net.ssl.SSLContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, null, null);

CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(context)
    .build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);

推荐阅读