httpclient点击超时,但服务器可用且工作正常

bgibtngc  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(223)

我的问题是httpclient从来没有到达目标。目标是在同一个网络上(所以我不需要代理),它肯定是向上的。而且超时设置得相当高(120秒),服务器能够在不到一秒钟的时间内做出响应。使用其他应用程序或 curl 一切正常。
这是我的代码,我尝试了两种设置凭据的方法,它们都用注解标记。在我的测试中,我先启用了一个,然后启用了另一个:

  1. HttpRequest request = HttpRequest.newBuilder()
  2. .uri(new URI( "https://target:8443/foo/bar"))
  3. .version(HttpClient.Version.HTTP_1_1)
  4. // approach 1:
  5. .header("Authorization", basicAuth("foo", "bar"))
  6. .timeout(Duration.ofSeconds(120)).POST(HttpRequest.BodyPublishers.ofFile(tempFile.toPath())).build();
  7. HttpResponse<String> response = HttpClient.newBuilder()
  8. /* approach 2:
  9. .authenticator(new Authenticator() {
  10. @Override
  11. protected PasswordAuthentication getPasswordAuthentication() {
  12. System.err.println("Was asked for a password");
  13. return new PasswordAuthentication("foo", "bar".toCharArray());
  14. }
  15. })
  16. */
  17. .followRedirects(HttpClient.Redirect.ALWAYS)
  18. .build()
  19. .send(request, HttpResponse.BodyHandlers.ofString());

与此相反,这一点很有效:

  1. curl -u foo:bar -X POST -H "content-type: application/vnd.lucidworks-document" https://target:8443/foo/bar --data-binary @test.json -v

我的java代码引发以下错误:

  1. 2021-04-25 10:26:56.730 INFO 12316 --- [SelectorManager] jdk.httpclient.HttpClient CHANNEL: Read error signalled on channel java.nio.channels.SocketChannel[closed]: java.io.IOException: connection closed locally
  2. at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:561)
  3. at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:119)
  4. ...
  5. Caused by: java.net.ConnectException: Connection timed out: no further information
  6. at java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
  7. at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:779)
  8. at java.net.http/jdk.internal.net.http.PlainHttpConnection$ConnectEvent.handle(PlainHttpConnection.java:128)
  9. at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.handleEvent(HttpClientImpl.java:957)
  10. at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.lambda$run$3(HttpClientImpl.java:912)
  11. at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
  12. at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:912)

启用的日志不会显示太多,但这行代码让我觉得身份验证可能不起作用,因此连接会“卡住”?!?

  1. MISC: Applying jdk.internal.net.http.AuthenticationFilter@43b3184

我知道有些版本的java存在我描述的问题,但我在当前版本的OpenJDKJava11(11.0.11+9)和15(15.0.2+7)上尝试了这个方法,仍然有相同的体验。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题