java.net.http.HttpClient是否需要关闭?

时间:2019-06-05 22:40:41

标签: java java-http-client

我使用的是新的java.net.http.HttpClient,在经过约378026次调用之后,根据我的测试,我开始得到以下内容

Caused by: java.net.ConnectException: Cannot assign requested address
        at java.net.http/jdk.internal.net.http.common.Utils.toConnectException(Utils.java:964)
        at java.net.http/jdk.internal.net.http.PlainHttpConnection.connectAsync(PlainHttpConnection.java:179)
        at java.net.http/jdk.internal.net.http.AsyncSSLConnection.connectAsync(AsyncSSLConnection.java:56)
        at java.net.http/jdk.internal.net.http.Http2Connection.createAsync(Http2Connection.java:369)
        at java.net.http/jdk.internal.net.http.Http2ClientImpl.getConnectionFor(Http2ClientImpl.java:127)
        at java.net.http/jdk.internal.net.http.ExchangeImpl.get(ExchangeImpl.java:88)
        at java.net.http/jdk.internal.net.http.Exchange.establishExchange(Exchange.java:293)
        at java.net.http/jdk.internal.net.http.Exchange.responseAsyncImpl0(Exchange.java:425)
        at java.net.http/jdk.internal.net.http.Exchange.responseAsyncImpl(Exchange.java:330)
        at java.net.http/jdk.internal.net.http.Exchange.responseAsync(Exchange.java:322)
        at java.net.http/jdk.internal.net.http.MultiExchange.responseAsyncImpl(MultiExchange.java:304)
        at java.net.http/jdk.internal.net.http.MultiExchange.lambda$responseAsync0$2(MultiExchange.java:250)
        at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1072)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1705)
        at java.net.http/jdk.internal.net.http.HttpClientImpl$DelegatingExecutor.execute(HttpClientImpl.java:153)
        at java.base/java.util.concurrent.CompletableFuture.completeAsync(CompletableFuture.java:2591)
        at java.net.http/jdk.internal.net.http.MultiExchange.responseAsync(MultiExchange.java:204)
        at java.net.http/jdk.internal.net.http.HttpClientImpl.sendAsync(HttpClientImpl.java:632)

下面是我使用的课程

public class JavaHttpClient {
    HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30))
            .followRedirects(HttpClient.Redirect.ALWAYS).build();

    public String getRequest(String incomingUrl) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(incomingUrl)).GET().build();
        HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());

        return response.body();
    }

}

我不明白为什么会这样。我以为应该关闭一些东西?

1 个答案:

答案 0 :(得分:0)

HttpClient将在不再被引用并且没有正在进行的操作(已收到所有响应)时关闭所有打开的连接。