Language: Java
Networking/HTTP
HttpClient was created to simplify HTTP communication in Java applications. It abstracts the complexities of HTTP connections, supports synchronous and asynchronous operations, and provides utilities for headers, cookies, and authentication. Widely used in web services, REST clients, and integrations, it ensures reliable and maintainable HTTP communication.
Apache HttpClient is a robust and feature-rich HTTP client library for Java. It allows sending HTTP requests, handling responses, managing connections, cookies, authentication, and supporting advanced features like redirects and timeouts.
Add dependency in pom.xml:
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2</version>
</dependency>Add dependency in build.gradle:
implementation 'org.apache.httpcomponents.client5:httpclient5:5.2'HttpClient allows creating HTTP requests (GET, POST, PUT, DELETE), handling responses, managing cookies, setting headers, handling timeouts, and supporting connection pooling. It supports both synchronous and asynchronous request execution.
import org.apache.hc.client5.http.fluent.Request;
String response = Request.get("https://httpbin.org/get").execute().returnContent().asString();
System.out.println(response);Performs a simple GET request and prints the response content.
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.io.entity.StringEntity;
String json = "{\"key\": \"value\"}";
String response = Request.post("https://httpbin.org/post")
.bodyString(json, org.apache.hc.core5.http.ContentType.APPLICATION_JSON)
.execute().returnContent().asString();
System.out.println(response);Sends a POST request with JSON payload and prints the response.
import org.apache.hc.client5.http.fluent.Request;
String response = Request.get("https://httpbin.org/headers")
.addHeader("User-Agent", "MyHttpClient/1.0")
.execute().returnContent().asString();
System.out.println(response);Adds custom headers to the request.
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.classic.methods.HttpGet;
RequestConfig config = RequestConfig.custom().setResponseTimeout(5_000).build();
try (CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build()) {
HttpGet request = new HttpGet("https://httpbin.org/delay/10");
client.execute(request);
} catch (Exception e) {
System.out.println("Request timed out");
}Sets a timeout to prevent indefinite waiting.
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(50);
cm.setDefaultMaxPerRoute(10);
CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();Manages multiple HTTP connections efficiently using a connection pool.
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new UsernamePasswordCredentials("user", "password".toCharArray()));
CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();Sets up basic authentication for requests.
Use connection pooling for high-performance applications.
Always set timeouts to avoid hanging requests.
Use fluent API for simpler code and readability.
Handle exceptions like IOExceptions to ensure reliability.
Close resources properly using try-with-resources or clients’ close() methods.