A comprehensive Java HTTP client management system. Provides scalable, robust HTTP communication capabilities.
- Java 11 or higher
- Maven
The HTTP Manager system is built using several design patterns to ensure maintainability, scalability, and ease of use:
- Singleton Pattern -
HttpManager
provides a single instance for the entire application. - Strategy Pattern -
HttpClient
interface allows different HTTP client implementations. - Builder Pattern -
HttpRequest
andHttpClientConfig
use builder pattern for easy construction. - Facade Pattern -
HttpManager
provides a simplified interface to complex HTTP operations. - Factory Pattern - Easy creation of HTTP clients with different configurations.
SimpleHttpManager/
├── Clients/
├── HttpClient.java # Interface for HTTP operations
├── ApacheHttpClient.java # Apache HttpClient 5 implementation
└── HttpClientConfig.java # Configuration class
├── Entities/
├── HttpRequest.java # Request DTO
└── HttpResponse.java # Response DTO
├── Enums/
└── HttpMethod.java # HTTP methods enum
├── Examples/
├── ApiService.java # Service layer for API operations
└── HttpManagerExample.java # Usage examples and documentation
├── HttpManager.java # Main facade class (Singleton)
└── HttpException.java # Custom exception for HTTP errors
- Connection Pooling - Efficient connection management with configurable pool sizes
- Retry Mechanism - Automatic retry with exponential backoff
- Timeout Management - Configurable connection and read timeouts
- Header Management - Default headers and custom header support
- Error Handling - Comprehensive error handling with custom exceptions
- Logging - Detailed logging for debugging and monitoring
- JSON Support - Built-in JSON request/response handling
- Authentication - Bearer token support for API authentication
- Redirect Handling - Configurable redirect following
- Custom User Agents - Configurable user agent strings
- Response Validation - Helper methods for response status checking
- Resource Management - Proper cleanup of HTTP resources
Add the following code to your pom.xml
file:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<!-- Simple HTTP Manager System -->
<dependency>
<groupId>com.github.FourteenDev</groupId>
<artifactId>simple-http-manager</artifactId>
<version>v1.0.0</version>
</dependency>
</dependencies>
// Get the HTTP manager instance
HttpManager httpManager = HttpManager.getInstance();
// Simple GET request
HttpResponse response = httpManager.get("https://api.example.com/data");
// Simple POST request with JSON
JSONObject data = new JSONObject();
data.put("name", "John Doe");
data.put("email", "[email protected]");
HttpResponse postResponse = httpManager.post("https://api.example.com/users", data);
// Create custom configuration
HttpClientConfig config = new HttpClientConfig()
.connectionTimeout(5000) // 5 seconds
.readTimeout(15000) // 15 seconds
.maxConnections(20) // Max 20 connections
.maxRetries(3) // Retry failed requests 3 times
.retryDelay(Duration.ofSeconds(2)) // Wait 2 seconds between retries
.userAgent("MyApp/1.0"); // Custom user agent
// Get instance with custom configuration
HttpManager httpManager = HttpManager.getInstance(config);
The HttpClientConfig
class provides comprehensive configuration options:
Property | Default | Description |
---|---|---|
connectionTimeout |
10000ms | Connection establishment timeout |
readTimeout |
30000ms | Response read timeout |
maxConnections |
20 | Maximum total connections |
maxConnectionsPerRoute |
10 | Maximum connections per route |
followRedirects |
true | Whether to follow redirects |
userAgent |
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" | User agent string |
enableRetry |
true | Enable automatic retry |
maxRetries |
3 | Maximum retry attempts |
retryDelay |
1 second | Delay between retries |
The HTTP Manager automatically includes these default headers:
Content-Type: application/json
Accept: application/json
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
You can add custom headers:
HttpManager httpManager = HttpManager.getInstance();
httpManager.addDefaultHeader("X-API-Key", "your-api-key");
httpManager.addDefaultHeader("Authorization", "Bearer your-token");
The system uses HttpException
for all HTTP-related errors:
try {
HttpResponse response = httpManager.get("https://api.example.com/data");
// Process response
} catch (HttpException e) {
if (e.hasStatusCode())
logger.error("HTTP error {}: {}", e.getStatusCode(), e.getMessage());
else
logger.error("Network error: {}", e.getMessage());
}
The HttpResponse
class provides helper methods:
HttpResponse response = httpManager.get("https://api.example.com/data");
if (response.isSuccess())
{
// Process successful response
} else if (response.isClientError()) {
// Handle client errors (4xx)
} else if (response.isServerError()) {
// Handle server errors (5xx)
}
Always close the HTTP manager when done:
HttpManager httpManager = HttpManager.getInstance();
try {
// Use HTTP manager
} finally {
httpManager.close();
}
Always handle exceptions properly:
try {
HttpResponse response = httpManager.get(url);
// Process response
} catch (HttpException e) {
logger.error("HTTP request failed", e);
// Handle error appropriately
}
Use appropriate timeouts and retry settings for your use case:
HttpClientConfig config = new HttpClientConfig()
.connectionTimeout(5000) // Shorter for fast-fail scenarios
.readTimeout(30000) // Longer for slow APIs
.maxRetries(3) // Retry transient failures
.retryDelay(Duration.ofSeconds(1)); // Exponential backoff
The system provides comprehensive logging. Configure your logging level appropriately:
# In logback.xml or similar
<logger name="dev.PACKAGENAME.PROJECTNAME.HttpManager" level="DEBUG"/>
- Apache HttpClient 5.3.1
- Apache HttpClient Fluent API 5.3.1
- JSON in Java 20250517
- SLF4J API 2.0.11
- Default: 20 total connections, 10 per route
- Configurable based on your needs
- Automatic connection reuse
Configure timeouts based on your API characteristics:
- Fast APIs: Lower timeouts (5-10 seconds)
- Slow APIs: Higher timeouts (30-60 seconds)
- Batch operations: Higher timeouts for large payloads
The retry mechanism helps with transient failures:
- Default: 3 retries with 1-second delay
- Exponential backoff for better reliability
- Configurable retry conditions
-
Connection Timeouts
- Increase
connectionTimeout
in configuration - Check network connectivity
- Verify API endpoint availability
- Increase
-
Read Timeouts
- Increase
readTimeout
for slow APIs - Check API response times
- Consider API optimization
- Increase
-
Authentication Errors
- Verify API token in configuration
- Check token expiration
- Ensure proper header format
-
Rate Limiting
- Implement request throttling
- Add delays between requests
- Check API rate limits
Enable debug logging for troubleshooting:
// Add debug headers to see what's being sent
httpManager.addDefaultHeader("X-Debug", "true");
// Check response details
HttpResponse response = httpManager.get(url);
logger.debug("Response: {}", response);
Potential improvements for the HTTP Manager:
- Circuit Breaker Pattern - Automatic failure detection and recovery
- Request/Response Interceptors - Custom processing hooks
- Metrics Collection - Performance monitoring
- Async Support - Non-blocking HTTP operations
- Caching - Response caching for repeated requests
- Compression - Automatic request/response compression
For issues or questions about the HTTP Manager:
- Check the example code in
HttpManagerExample.java
- Review the logging output for error details
- Verify configuration settings
- Test with simple requests first
mvn clean install
mvn compile exec:java -Dexec.mainClass="dev.Fourteen.SimpleHttpManager.Examples.HttpManagerExample"