Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing HttpClient connection before timout is reached

I am currently using the HTTPClient 4 to make a POST request to a remote server like this:

  HttpResponse response = httpClient.execute( request );
  InputStream is = response.getEntity().getContent();

When the server is not reachable it takes a self-configured amount of time before the connection actually times out. During that periode the execute() is a blocking call.

What i am looking for is a way to cancel the execute() before the natural timeout so that my thread running the execute() is not blocked anymore and will finish gracefully.

I have tried

request.abort();

and

httpClient.getConnectionManager().shutdown();

But both of these calls do not interrupt the execute(). Is there any other way to cancel the ongoing connection attempt?

like image 998
Moritz Avatar asked Dec 29 '11 15:12

Moritz


People also ask

Do we need to close HttpClient connection?

If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself.

When should I close HttpClient?

You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.

What is connection timeout in HttpClient?

timeout) – the time waiting for data – after establishing the connection; maximum time of inactivity between two data packets. the Connection Manager Timeout (http. connection-manager. timeout) – the time to wait for a connection from the connection manager/pool.

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.


1 Answers

Wrap the call in a Future and invoke get with timeout.

like image 78
alphazero Avatar answered Nov 01 '22 20:11

alphazero