Java 10孵化器HttpClient请求Node.js本地服务器失败
解决Java 9/10孵化器HttpClient访问本地服务器抛出EOFException的问题
最近在测试Java 9/10孵化器中的jdk.incubator.httpclient组件时,碰到了一个挺棘手的问题:用官方示例代码发送GET请求时,访问外部非本地URL完全正常,但请求本地服务器——不管是用localhost、127.0.0.1还是本机实际IP——都会直接失败,抛出EOFException,而且堆栈信息完全不涉及我自己写的业务代码。
测试代码
我用的是项目主页提供的基础示例代码:
URI uri = URI.create("http://192.168.1.102:8080/"); HttpRequest getRequest = HttpRequest.newBuilder() .uri(uri) .GET() .build(); HttpResponse<String> response = client.send(getRequest, HttpResponse.BodyHandler.asString()); System.out.println("response to get: " + response.body());
报错信息
运行时会先弹出孵化器模块的警告,随后直接抛出异常:
WARNING: Using incubator modules: jdk.incubator.httpclient Exception in thread "main" java.io.EOFException: EOF reached while reading at jdk.incubator.httpclient/jdk.incubator.http.Http1AsyncReceiver$Http1TubeSubscriber.onComplete(Http1AsyncReceiver.java:507) at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$ReadSubscription.signalCompletion(SocketTube.java:551) at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$InternalReadSubscription.read(SocketTube.java:728) at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$SocketFlowTask.run(SocketTube.java:171) at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$SchedulableTask.run(SequentialScheduler.java:198) at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:271) at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:224) at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$InternalReadSubscription.signalReadable(SocketTube.java:675) at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$ReadEvent.signalEvent(SocketTube.java:829) at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$SocketFlowEvent.handle(SocketTube.java:243) at jdk.incubator.httpclient/jdk.incubator.http.HttpClientImpl$SelectorManager.handleEvent(HttpClientImpl.java:769) at jdk.incubator.httpclient/jdk.incubator.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:731)
排查与解决
一开始我怀疑是本地服务器没启动,但用浏览器可以正常访问,直接排除了这个可能。后来反复测试排查,发现问题根源和我当时用的Node.js/Express服务器的HTTP/2协议升级处理逻辑有关——这个孵化器版本的HttpClient在和这类服务器交互时,协议协商阶段可能出现了异常,导致连接提前断开,进而抛出EOF错误。
最后我更换了其他HTTP服务器进行测试,这个问题就完全消失了。
内容的提问来源于stack exchange,提问作者Toby Eggitt
相关产品推荐
相关产品推荐

