Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set socket timeout in Java HTTP Client

We want to migrate all our apache-httpclient-4.x code to java-http-client code to reduce dependencies. While migrating them, i ran into the following issue under java 11:

How to set the socket timeout in Java HTTP Client?

With apache-httpclient-4.x we can set the connection timeout and the socket timeout like this:

DefaultHttpClient httpClient = new DefaultHttpClient();
int timeout = 5; // seconds
HttpParams httpParams = httpClient.getParams();
httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout * 1000);
httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout * 1000);

With java-http-client i can only set the connection timeout like this:

HttpClient httpClient = HttpClient.newBuilder()
                                  .connectTimeout(Duration.ofSeconds(5))
                                  .build()

But i found no way to set the socket timeout. Is there any way or an open issue to support that in the future?

like image 903
mseele Avatar asked Oct 27 '20 07:10

mseele


People also ask

How do I set timeout in HttpClient?

The default value is 100,000 milliseconds (100 seconds). To set an infinite timeout, set the property value to InfiniteTimeSpan. A Domain Name System (DNS) query may take up to 15 seconds to return or time out.

How do I set HTTP response timeout in Java?

The fluent, builder API introduced in 4.3 provides the right way to set timeouts at a high level: int timeout = 5; RequestConfig config = RequestConfig. custom() . setConnectTimeout(timeout * 1000) .

What is the default HTTP connection timeout?

The default value is 60 seconds. If the value of this stanza entry is set to 0 (or not set), connection timeouts between data fragments are governed instead by the client-connect-timeout stanza entry. The exception to this rule occurs for responses returned over HTTP (TCP).


1 Answers

You can specify it at the HttpRequest.Builder level via the timeout method:

HttpClient httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .build();

HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create("..."))
                .timeout(Duration.ofSeconds(5)) //this
                .build();


httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

If you've got connected successfully but not able to receive a response at the desired amount of time, java.net.http.HttpTimeoutException: request timed out will be thrown (in contrast with java.net.http.HttpConnectTimeoutException: HTTP connect timed out which will be thrown if you don't get a successful connection).

like image 137
amseager Avatar answered Oct 16 '22 19:10

amseager