CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-eclipse-jetty--jetty-client

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.

Pending
Overview
Eval results
Files

http-operations.mddocs/

HTTP Operations

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.

HttpClient Class

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();
}

Basic GET Operations

Simple synchronous GET requests that return a ContentResponse immediately.

GET with String URI

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();
}

GET with URI Object

URI uri = URI.create("https://api.example.com/data");
ContentResponse response = client.GET(uri);

Creating Custom Requests

For more complex requests, use the request factory methods that return a configurable Request object.

POST Request Factory

Request postRequest = client.POST("https://api.example.com/users");
// Further configure the request...
ContentResponse response = postRequest.send();

General Request Factory

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();

Request Sending Patterns

Synchronous Sending

Blocks until the response is complete:

ContentResponse response = request.send();

Asynchronous with Callback

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());
    }
});

CompletableFuture Pattern

Returns a CompletableFuture for async composition:

CompletableFuture<ContentResponse> future = request.send();
future.thenAccept(response -> {
    System.out.println("Received: " + response.getStatus());
});

Client Lifecycle

Starting and Stopping

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();
}

Configuration Before Starting

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 configuration

Error Handling

Synchronous Error Handling

try {
    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
}

Asynchronous Error Handling

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
        }
    }
});

Usage Examples

Simple REST API Client

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();
    }
}

Batch Request Processing

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

docs

authentication.md

connection-pooling.md

content-management.md

http-operations.md

index.md

proxy-configuration.md

request-configuration.md

response-processing.md

tile.json