Java-RestTemplate-连接被拒绝



我一直在疯狂地试图解决这个问题,很短,这是我用来执行对REST端点的调用的代码:

String url = "http://localhost:5000/getMyObject";
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(factory);
String result = restTemplate.getForObject(url, String.class);

但无论我添加什么标题,它总是以连接被拒绝而告终。

Stacktrace的代码段:

Caused by: java.net.ConnectException: Connection refused: connect
at java.base/java.net.PlainSocketImpl.waitForConnect(Native Method)
...
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776)
... 74 more

设置:在Windows上运行测试,在WSL 中运行应用程序

  • 它通过Curl工作(在控制台和我的测试中(
  • 如果测试本身启动应用程序,它就会工作
  • 它可以通过web浏览器工作

Curl-v:

localhost:5000/getMyObject
* Trying 127.0.0.1:5000
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 5000 (#0)
> GET /getMyObject HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.68.0
> Accept: */*
* Mark bundle as not supporting multiuse
< HTTP/1.1 200
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Sat, 22 Jan 2022 10:05:31 GMT
<
* Connection #0 to host localhost left intact
{<Data>}

SimpleClientHttpRequestFactory的某些功能不太好,我将其切换到HttpComponentsClientHttpRequestFactory,现在它运行得很好。

String url = "http://localhost:5000/getMyObject";
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory ();
RestTemplate restTemplate = new RestTemplate(factory);
String result = restTemplate.getForObject(url, String.class);

最新更新