RestTemplate 交换超时,但 PostMan 工作



我尝试使用Spring的RestTemplate发出一个简单的GET请求。

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers headers = new HttpHeaders() {
{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.US_ASCII));
String authHeader = "Basic " + new String(encodedAuth);
set(HttpHeaders.AUTHORIZATION, authHeader);
//set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());
}
};
ResponseEntity<FileTypeList> response = restTemplate.exchange(endpoint + FILES, HttpMethod.GET, new HttpEntity(headers), FileTypeList.class);
return response.getBody() != null ? response.getBody().getFileTypes() : Collections.emptyList();

此调用收到超时错误:

java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_161]
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_161]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_161]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_161]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_161]
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_161]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_161]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_161]
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:673) ~[na:1.8.0_161]

但是当我尝试与邮递员进行相同的通话时,它可以正常工作。

终结点 https://verda.borsaistanbul.com/files

Spring RestTemplate与邮递员有何不同?

"休息"模板允许您设置代理。有多种方法可以做到这一点,最简单的方法如下:

在创建 RestTemplate 之前,使用以下代码来设置代理:

Properties props = System.getProperties();
props.put("http.proxyHost", "your.proxy.server");
props.put("http.proxyPort", "80");

请注意,这将为 JVM 中的 while Java 应用程序设置代理。

设置代理的另一种方法如下,它将仅为当前代码设置代理:

SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("your.proxy.server", 80));
clientHttpReq.setProxy(proxy);
RestTemplate restTemplate = new RestTemplate(clientHttpReq);

这个解决方案对我有用;我实现了将代理添加到请求标头:

SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY, 80));
clientHttpReq.setProxy(proxy);

连接解决方案超时:

A. 代理配置:

SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY, 80));
clientHttpReq.setProxy(proxy);

B. 在 JRE 上禁用 IPv4 IP 的 IPv6 堆栈使用?

即使用 JVM 参数作为-Djava.net.preferIPv4Stack=true

相关内容

  • 没有找到相关文章

最新更新