Eclipse Jetty HTTP Client - A lightweight, asynchronous HTTP client library that supports HTTP/1.1, HTTP/2, WebSocket, and various authentication mechanisms, proxy configurations, and connection pooling strategies.
—
The core HTTP operations capability provides the fundamental HTTP client functionality for making GET, POST, PUT, DELETE and other HTTP requests with comprehensive request/response lifecycle management.
The main entry point for all HTTP operations.
public class HttpClient extends ContainerLifeCycle {
// Constructors
public HttpClient();
public HttpClient(HttpClientTransport transport);
public HttpClient(SslContextFactory.Client sslContextFactory);
// Lifecycle management
public void start() throws Exception;
public void stop() throws Exception;
public boolean isStarted();
public boolean isStopped();
// Simple GET operations (synchronous)
public ContentResponse GET(String uri) throws InterruptedException, ExecutionException, TimeoutException;
public ContentResponse GET(URI uri) throws InterruptedException, ExecutionException, TimeoutException;
// Request factory methods for POST
public Request POST(String uri);
public Request POST(URI uri);
// General request factory methods
public Request newRequest(String uri);
public Request newRequest(URI uri);
public Request newRequest(String host, int port);
// Configuration accessors
public RequestListeners getRequestListeners();
public HttpCookieStore getHttpCookieStore();
public void setHttpCookieStore(HttpCookieStore cookieStore);
public AuthenticationStore getAuthenticationStore();
public ProxyConfiguration getProxyConfiguration();
}Simple synchronous GET requests that return a ContentResponse immediately.
HttpClient client = new HttpClient();
client.start();
try {
ContentResponse response = client.GET("https://api.example.com/users");
System.out.println("Status: " + response.getStatus());
System.out.println("Content: " + response.getContentAsString());
} finally {
client.stop();
}URI uri = URI.create("https://api.example.com/data");
ContentResponse response = client.GET(uri);For more complex requests, use the request factory methods that return a configurable Request object.
Request postRequest = client.POST("https://api.example.com/users");
// Further configure the request...
ContentResponse response = postRequest.send();Request request = client.newRequest("https://api.example.com/data")
.method(HttpMethod.PUT)
.header("Authorization", "Bearer token123")
.content(new StringRequestContent("application/json", jsonData));
ContentResponse response = request.send();Blocks until the response is complete:
ContentResponse response = request.send();Non-blocking with callback notification:
request.send(result -> {
if (result.isSucceeded()) {
Response response = result.getResponse();
System.out.println("Success: " + response.getStatus());
} else {
System.err.println("Failed: " + result.getFailure());
}
});Returns a CompletableFuture for async composition:
CompletableFuture<ContentResponse> future = request.send();
future.thenAccept(response -> {
System.out.println("Received: " + response.getStatus());
});The HttpClient must be started before use and should be stopped when no longer needed:
HttpClient client = new HttpClient();
// Start the client (required before any requests)
client.start();
try {
// Make requests...
ContentResponse response = client.GET("https://example.com");
} finally {
// Always stop the client to release resources
client.stop();
}All configuration must be done before starting the client:
HttpClient client = new HttpClient();
// Configure before starting
client.setConnectTimeout(5000);
client.setIdleTimeout(30000);
client.setFollowRedirects(true);
client.start(); // Start after configurationtry {
ContentResponse response = client.GET("https://api.example.com/data");
if (response.getStatus() == 200) {
// Process successful response
String content = response.getContentAsString();
} else {
// Handle HTTP error status
System.err.println("HTTP Error: " + response.getStatus() + " " + response.getReason());
}
} catch (InterruptedException e) {
// Request was interrupted
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
// Request execution failed
Throwable cause = e.getCause();
if (cause instanceof HttpRequestException) {
// Request-related error
} else if (cause instanceof HttpResponseException) {
// Response-related error
}
} catch (TimeoutException e) {
// Request timed out
}request.send(result -> {
if (result.isSucceeded()) {
Response response = result.getResponse();
// Handle successful response
} else {
Throwable failure = result.getFailure();
if (failure instanceof HttpRequestException) {
// Request failed
} else if (failure instanceof HttpResponseException) {
// Response failed
} else {
// Other failure
}
}
});public class ApiClient {
private final HttpClient httpClient;
private final String baseUrl;
public ApiClient(String baseUrl) throws Exception {
this.httpClient = new HttpClient();
this.httpClient.start();
this.baseUrl = baseUrl;
}
public User getUser(long id) throws Exception {
ContentResponse response = httpClient.GET(baseUrl + "/users/" + id);
if (response.getStatus() == 200) {
return parseJson(response.getContentAsString(), User.class);
} else {
throw new ApiException("Failed to get user: " + response.getStatus());
}
}
public User createUser(User user) throws Exception {
String json = toJson(user);
ContentResponse response = httpClient.POST(baseUrl + "/users")
.header("Content-Type", "application/json")
.content(new StringRequestContent(json))
.send();
if (response.getStatus() == 201) {
return parseJson(response.getContentAsString(), User.class);
} else {
throw new ApiException("Failed to create user: " + response.getStatus());
}
}
public void close() throws Exception {
httpClient.stop();
}
}List<CompletableFuture<ContentResponse>> futures = new ArrayList<>();
for (String url : urls) {
CompletableFuture<ContentResponse> future = client.newRequest(url).send();
futures.add(future);
}
// Wait for all requests to complete
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0])
);
allFutures.thenRun(() -> {
for (CompletableFuture<ContentResponse> future : futures) {
try {
ContentResponse response = future.get();
System.out.println("Response: " + response.getStatus());
} catch (Exception e) {
System.err.println("Request failed: " + e.getMessage());
}
}
});Install with Tessl CLI
npx tessl i tessl/maven-org-eclipse-jetty--jetty-client