Http client java timeout

Java HttpClient Timeout Properties Explained with Examples

HTTP Request is a common integration approach used for building any reasonably sized application. However, just like in real life, a request is just a request and there is no guarantee a request would receive an appropriate response.

So what should be a developer do in this case?

In real-life we may be tempted to wait for a long time for a response. However, this is usually not the case in a typical software application. A user waiting for a response for an abnormally long time would be far more devastating to the business prospects of the application as compared to a failed response. Therefore, it is imperative that we make appropriate use of Timeouts when designing HTTP calls in our applications.

In this post, we will look at how to use configure Java HttpClient timeout properties.

1 – Types of Timeout

Mainly, there are three types of timeout properties that we can play around with:

  • Connection Timeout – The time taken to establish the connection with a remote host.
  • Socket Timeout – This is the time spent waiting for the data after the connection with the remote host has been established. In other words, it is the time between receiving two packets of data.
  • Connection Manager Timeout – Many hosts use a pool of connections to handle concurrent requests. This timeout deals with the time taken to receive an open connection from the pool.

In general, the first two parameters are the most important. However, in high load scenarios, we also need to be careful about properly setting the third timeout as well.

2 – Configuring HTTPClient Timeout Timeouts (the Old Fashioned Way)

Before version 4.3, we had to use normal parameters using generic map to configure HttpClient.

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); httpParams.setParameter( ClientPNames.CONN_MANAGER_TIMEOUT, new Long(timeout * 1000));

Here, we have setup the three parameters in the HttpClient object. The timeout is provided in milliseconds and therefore, we multiple the value by 1000. The properties CoreConnectionPNames are part of the org.apache.http package.

3 – Configuring Java HTTPClient Timeout Properties (the New Way)

With version 4.3, we have a much better way of setting the timeout properties. That is by using the HttpClient builder. See the below example for reference:

int timeout = 5; RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeout * 1000) .setConnectionRequestTimeout(timeout * 1000) .setSocketTimeout(timeout * 1000).build(); CloseableHttpClient httpClient= HttpClientBuilder.create().setDefaultRequestConfig(config).build();

This is a type-safe way to assigning the properties in a clean and error-free way. Therefore, in my view, this is the RECOMMENDED to configure HttpClient timeout properties in your application.

Читайте также:  Java приложение своими руками

4 – Usage of the HttpClient

After configuring the HttpClient, it is pretty straightforward to use it to make HTTP calls in your application. Example below:

HttpGet getMethod = new HttpGet("http://localhost:8080/path"); HttpResponse response = httpClient.execute(getMethod); System.out.println( "HTTP Status of response: " + response.getStatusLine().getStatusCode());

We can create an HTTP Client object for every request or customize its RequestConfig according to the needs of the application.

However, if we have uniform timeout rules, we can also define a standard HTTPClient object and use it to make HTTP Requests wherever needed. If we are using a Spring-based application, we can very easily declare HttpClient as a bean and inject it using Spring Dependency Injection wherever required.

With this, we have successfully looked at Java HttpClient Timeout Properties and configuring the same for our application. If you have any comments or queries, please do mention in the comments section.

Источник

Java HttpClient Timeout

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Читайте также:  Php request time float

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll show how to set up a timeout with the new Java HTTP client available from Java 11 onwards and the Java.

In case we need to refresh our knowledge, we can start with the tutorial on Java HTTP Client.

On the other hand, to learn how to set up a timeout using the older library, see HttpUrlConnection.

2. Configuring a Timeout

First of all, we need to set up an HttpClient to be able to make an HTTP request:

private static HttpClient getHttpClientWithTimeout(int seconds)

Above, we created a method that returns a HttpClient configured with a timeout defined as a parameter. Shortly, we use the Builder design pattern to instantiate an HttpClient and configure the timeout using the connectTimeout method. Additionally, using the static method ofSeconds, we created an instance of the Duration object that defines our timeout in seconds.

After that, we check if the HttpClient timeout is configured correctly:

httpClient.connectTimeout().map(Duration::toSeconds) .ifPresent(sec -> System.out.println("Timeout in seconds: " + sec));

So, we use the connectTimeout method to get the timeout. As a result, it returns an Optional of Duration, which we mapped to seconds.

3. Handling Timeouts

Further, we need to create an HttpRequest object that our client will use to make an HTTP request:

HttpRequest httpRequest = HttpRequest.newBuilder() .uri(URI.create("http://10.255.255.1")).GET().build();

To simulate a timeout, we make a call to a non-routable IP address. In other words, all the TCP packets drop and force a timeout after the predefined duration as configured earlier.

Читайте также:  Java беззнаковый тип данных

Now, let’s take a deeper look at how to handle a timeout.

3.1. Handling Synchronous Call Timeout

For example, to make the synchronous call use the send method:

HttpConnectTimeoutException thrown = assertThrows( HttpConnectTimeoutException.class, () -> httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()), "Expected send() to throw HttpConnectTimeoutException, but it didn't"); assertTrue(thrown.getMessage().contains("timed out"));

The synchronous call forces to catch the IOException, which the HttpConnectTimeoutException extends. Consequently, in the test above, we expect the HttpConnectTimeoutException with an error message.

3.2. Handling Asynchronous Call Timeout

Similarly, to make the asynchronous call use the sendAsync method:

CompletableFuture completableFuture = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .exceptionally(Throwable::getMessage); String response = completableFuture.get(5, TimeUnit.SECONDS); assertTrue(response.contains("timed out"));

The above call to sendAsync returns a CompletableFuture . Consequently, we need to define how to handle the response functionally. In detail, we get the body from the response when no error occurs. Otherwise, we get the error message from the throwable. Finally, we get the result from the CompletableFuture by waiting a maximum of 5 seconds. Again, this request throws an HttpConnectTimeoutException as we expect just after 3 seconds.

4. Configure Timeout at the Request Level

Above, we reused the same client instance for both the sync and async call. However, we might want to handle the timeout differently for each request. Likewise, we can set up the timeout for a single request:

HttpRequest httpRequest = HttpRequest.newBuilder() .uri(URI.create("http://10.255.255.1")) .timeout(Duration.ofSeconds(1)) .GET() .build();

Similarly, we are using the timeout method to set up the timeout for this request. Here, we configured the timeout of 1 second for this request.

The minimum duration between the client and the request sets the timeout for the request.

5. Conclusions

In this article, we successfully configure a timeout using the new Java HTTP Client and handle a request gracefully when timeouts overflow.

And as always, the source code for the examples is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью