Apache HttpComponents Cleint, commonly referred to as HttpClient, is an open-source Java libray built for sending HTTP requests and processing corresponding responses. It exposes a user-friendly API suite for constructing, executing HTTP requests, and managing all components of request/response workflows, including URI parsing, header configuration, payload construction, response status validation, and resposne body parsing.
Below are implementations of common HTTP operations using the library:
Send GET Request
// Initialize default HTTP client instance
try (CloseableHttpClient webClient = HttpClients.createDefault()) {
// Define GET request target
HttpGet getRequest = new HttpGet("https://sample-api.com/data");
// Execute request and capture response
try (CloseableHttpResponse apiResponse = webClient.execute(getRequest)) {
// Extract response status code
int responseStatus = apiResponse.getStatusLine().getStatusCode();
// Convert response entity to string with explicit charset
String responseContent = EntityUtils.toString(apiResponse.getEntity(), StandardCharsets.UTF_8);
// Custom response processing logic goes here
}
} catch (IOException e) {
// Handle request execution exceptions
e.printStackTrace();
}
Send Form POST Request
try (CloseableHttpClient webClient = HttpClients.createDefault()) {
HttpPost postRequest = new HttpPost("https://sample-api.com/submit");
// Populate form parameters
List<NameValuePair> formFields = new ArrayList<>();
formFields.add(new BasicNameValuePair("username", "test_user"));
formFields.add(new BasicNameValuePair("password", "secure_pass_123"));
postRequest.setEntity(new UrlEncodedFormEntity(formFields, StandardCharsets.UTF_8));
try (CloseableHttpResponse apiResponse = webClient.execute(postRequest)) {
// Process response as required
}
} catch (IOException e) {
e.printStackTrace();
}
Configure Custom Request Headers
// Add custom headers to requests
getRequest.addHeader("Accept", "application/json");
postRequest.setHeader("X-API-Key", "ak_8a7d6f5e4b3c2a10");
Handle Multipart File Upload
try (CloseableHttpClient webClient = HttpClients.createDefault()) {
HttpPost uploadRequest = new HttpPost("https://sample-api.com/asset/upload");
// Load local file for upload
File targetFile = new File("/home/user/documents/report.pdf");
// Build multipart request entity with additional metadata
HttpEntity uploadEntity = MultipartEntityBuilder.create()
.addBinaryBody("upload_file", targetFile, ContentType.APPLICATION_PDF, targetFile.getName())
.addTextBody("upload_category", "reports")
.build();
uploadRequest.setEntity(uploadEntity);
try (CloseableHttpResponse apiResponse = webClient.execute(uploadRequest)) {
// Process upload response
}
} catch (IOException e) {
e.printStackTrace();
}
Enable Automatic Redirect Following
// Configure client to automatically follow all valid redirects
CloseableHttpClient redirectEnabledClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
// Execute requests with the configured client as needed
The examples above cover only basic usage of the Apache HttpComponents Client library. It also supports a wide range of advanced configuration options and extended capabilities, including connection pool management, proxy server setup, custom request timeout rules, SSL/TLS context configuration, cookie persistence, and request/response interceptor chains to meet complex HTTP communication requirements.