我的问题是httpclient从来没有到达目标。目标是在同一个网络上(所以我不需要代理),它肯定是向上的。而且超时设置得相当高(120秒),服务器能够在不到一秒钟的时间内做出响应。使用其他应用程序或 curl
一切正常。
这是我的代码,我尝试了两种设置凭据的方法,它们都用注解标记。在我的测试中,我先启用了一个,然后启用了另一个:
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI( "https://target:8443/foo/bar"))
.version(HttpClient.Version.HTTP_1_1)
// approach 1:
.header("Authorization", basicAuth("foo", "bar"))
.timeout(Duration.ofSeconds(120)).POST(HttpRequest.BodyPublishers.ofFile(tempFile.toPath())).build();
HttpResponse<String> response = HttpClient.newBuilder()
/* approach 2:
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.err.println("Was asked for a password");
return new PasswordAuthentication("foo", "bar".toCharArray());
}
})
*/
.followRedirects(HttpClient.Redirect.ALWAYS)
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
与此相反,这一点很有效:
curl -u foo:bar -X POST -H "content-type: application/vnd.lucidworks-document" https://target:8443/foo/bar --data-binary @test.json -v
我的java代码引发以下错误:
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
at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:561)
at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:119)
...
Caused by: java.net.ConnectException: Connection timed out: no further information
at java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:779)
at java.net.http/jdk.internal.net.http.PlainHttpConnection$ConnectEvent.handle(PlainHttpConnection.java:128)
at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.handleEvent(HttpClientImpl.java:957)
at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.lambda$run$3(HttpClientImpl.java:912)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:912)
启用的日志不会显示太多,但这行代码让我觉得身份验证可能不起作用,因此连接会“卡住”?!?
MISC: Applying jdk.internal.net.http.AuthenticationFilter@43b3184
我知道有些版本的java存在我描述的问题,但我在当前版本的OpenJDKJava11(11.0.11+9)和15(15.0.2+7)上尝试了这个方法,仍然有相同的体验。
暂无答案!
目前还没有任何答案,快来回答吧!