How to Set a Timeout for Apache HttpClient Execution

Question

How can I configure a timeout for the entire execution of Apache HttpClient?

httpClient.getParams().setParameter("http.socket.timeout", timeout * 1000);
httpClient.getParams().setParameter("http.connection.timeout", timeout * 1000);
httpClient.getParams().setParameter("http.connection-manager.timeout", new Long(timeout * 1000));
httpClient.getParams().setParameter("http.protocol.head-body-timeout", timeout * 1000);

Answer

Setting a timeout for Apache HttpClient is crucial for preventing indefinite hangs during HTTP requests. Properly configuring timeouts ensures that your application can gracefully handle cases where the remote host is unresponsive or slow.

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

int timeout = 10; // timeout in seconds
RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(timeout * 1000)
    .setSocketTimeout(timeout * 1000)
    .setConnectionRequestTimeout(timeout * 1000)
    .build();

CloseableHttpClient httpClient = HttpClients.custom()
    .setDefaultRequestConfig(requestConfig)
    .build();

Causes

  • The default timeout settings might not interrupt ongoing data transfers if they are still receiving data, regardless of the specified timeout.
  • In some cases, the server might be slow to respond or might never complete sending its data, causing the connection to remain open indefinitely.

Solutions

  • Use `RequestConfig` to set connection, socket, and connection manager timeouts explicitly for better control.
  • Implement request timeouts using the new HttpClient API (`HttpClientBuilder`, `CloseableHttpClient`, etc.) to provide a more modern approach.

Common Mistakes

Mistake: Not setting socket timeout, which leads to indefinite hang when the server is slow.

Solution: Always set the socket timeout along with connection timeouts.

Mistake: Using deprecated Apache HttpClient methods and classes.

Solution: Utilize the latest HttpClient API, like `CloseableHttpClient`, for better configurability and support.

Helpers

  • Apache HttpClient timeout
  • HttpClient timeout settings
  • configure HttpClient timeout
  • Apache HttpClient connection timeout

Related Questions

⦿Why Does getResourceAsStream Return Null in JUnit Tests?

Discover why getResourceAsStream returns null in JUnit tests and how to fix it. Explore solutions with code examples and common mistakes.

⦿How Can I Achieve Functionality Similar to ltrim() and rtrim() in Java?

Discover effective alternatives to JavaScripts ltrim and rtrim functions for trimming whitespace in Java.

⦿How to Update Metadata for an Existing File on Amazon S3 Using JClouds?

Learn how to update metadata like cache control headers for S3 files using the JClouds API.

⦿Can You Pass a Username and Password in Maven Deploy from the Command Line?

Learn how to pass username and password values directly in Maven Deploy using command line arguments for secure repository access.

⦿What is the purpose of PartitioningBy in Java Streams?

Learn about the purpose of partitioningBy in Java Streams and how it compares with groupingBy.

⦿How to Change Time Zone in Joda-Time Without Altering the Timestamp

Learn how to convert time zones in JodaTime without affecting the actual timestamp value. Stepbystep instructions and code examples.

⦿Understanding the Purpose of the Non-Sealed Class in Java's Sealed Classes

Explore the implications and reasons for using nonsealed classes in Java especially in the context of JEP 360.

⦿How to Calculate Percentage from Two Integers in Programming?

Learn how to accurately calculate the percentage from two integers in programming with clear code examples and explanations.

⦿Understanding the Backpressure Mechanism in Spring WebFlux

Learn how to implement backpressure in Spring WebFlux to balance request and response rates effectively.

⦿How to Reformat a Simple Date String in Java/Groovy Without Errors?

Learn how to properly reformat date strings in Java and Groovy addressing common parsing issues and providing code examples.

© Copyright 2025 - CodingTechRoom.com