CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-apache-httpcomponents--httpclient

Apache HttpComponents Client is a library of components for building client side HTTP services

Pending
Overview
Eval results
Files

response-handling.mddocs/

Response Handling

Apache HttpClient provides flexible response processing capabilities including handler interfaces, closeable responses for proper resource management, and utility methods for content extraction and status code handling.

Response Interfaces

HttpResponse

public interface HttpResponse extends HttpMessage {
    StatusLine getStatusLine();
    void setStatusLine(StatusLine statusline);
    void setStatusLine(ProtocolVersion ver, int code);
    void setStatusLine(ProtocolVersion ver, int code, String reason);
    void setStatusCode(int code);
    void setReasonPhrase(String reason);
    HttpEntity getEntity();
    void setEntity(HttpEntity entity);
    Locale getLocale();
    void setLocale(Locale loc);
}

Base interface for HTTP responses containing status line, headers, and entity.

CloseableHttpResponse

public interface CloseableHttpResponse extends HttpResponse, Closeable {
    void close() throws IOException;
}

HTTP response that implements Closeable for proper resource management.

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        String responseBody = EntityUtils.toString(entity);
        System.out.println(responseBody);
    }
}

Response Handlers

ResponseHandler Interface

public interface ResponseHandler<T> {
    T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;
}

Strategy interface for processing HTTP responses and converting them to desired types.

Basic Response Handler

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
    @Override
    public String handleResponse(HttpResponse response) throws IOException {
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    }
};

String responseBody = httpClient.execute(httpGet, responseHandler);

JSON Response Handler Example

ResponseHandler<JsonObject> jsonHandler = new ResponseHandler<JsonObject>() {
    @Override
    public JsonObject handleResponse(HttpResponse response) throws IOException {
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String json = EntityUtils.toString(entity);
                return JsonParser.parseString(json).getAsJsonObject();
            }
        }
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

JsonObject jsonResponse = httpClient.execute(httpGet, jsonHandler);

Status Line Processing

StatusLine Interface

public interface StatusLine {
    ProtocolVersion getProtocolVersion();
    int getStatusCode();
    String getReasonPhrase();
}

Interface representing the HTTP response status line.

CloseableHttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
ProtocolVersion protocolVersion = statusLine.getProtocolVersion();

System.out.println("Status: " + statusCode + " " + reasonPhrase);
System.out.println("Protocol: " + protocolVersion);

Entity Processing

HttpEntity Interface

public interface HttpEntity {
    boolean isRepeatable();
    boolean isChunked();
    long getContentLength();
    Header getContentType();
    Header getContentEncoding();
    InputStream getContent() throws IOException, UnsupportedOperationException;
    void writeTo(OutputStream outstream) throws IOException;
    boolean isStreaming();
    void consumeContent() throws IOException;
}

Interface representing HTTP message entity (request or response body).

EntityUtils

public final class EntityUtils {
    public static void consume(HttpEntity entity) throws IOException;
    public static void consumeQuietly(HttpEntity entity);
    public static String toString(HttpEntity entity) throws IOException, ParseException;
    public static String toString(HttpEntity entity, String defaultCharset) throws IOException, ParseException;
    public static String toString(HttpEntity entity, Charset defaultCharset) throws IOException, ParseException;
    public static byte[] toByteArray(HttpEntity entity) throws IOException;
    public static void updateEntity(HttpResponse response, HttpEntity entity) throws IOException;
}

Utility methods for working with HTTP entities.

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    
    // Convert to string
    String responseBody = EntityUtils.toString(entity);
    
    // Convert to byte array
    byte[] responseBytes = EntityUtils.toByteArray(entity);
    
    // Get content length
    long contentLength = entity.getContentLength();
    
    // Check if repeatable
    boolean repeatable = entity.isRepeatable();
    
    // Consume entity to free resources
    EntityUtils.consume(entity);
}

Content Type Handling

ContentType

public final class ContentType {
    public static final ContentType APPLICATION_ATOM_XML;
    public static final ContentType APPLICATION_FORM_URLENCODED;
    public static final ContentType APPLICATION_JSON;
    public static final ContentType APPLICATION_OCTET_STREAM;
    public static final ContentType APPLICATION_SVG_XML;
    public static final ContentType APPLICATION_XHTML_XML;
    public static final ContentType APPLICATION_XML;
    public static final ContentType MULTIPART_FORM_DATA;
    public static final ContentType TEXT_HTML;
    public static final ContentType TEXT_PLAIN;
    public static final ContentType TEXT_XML;
    public static final ContentType WILDCARD;
    
    public static ContentType create(String mimeType);
    public static ContentType create(String mimeType, Charset charset);
    public static ContentType create(String mimeType, String charset);
    public static ContentType parse(String s) throws ParseException, UnsupportedCharsetException;
    public static ContentType get(HttpEntity entity) throws ParseException, UnsupportedCharsetException;
    public static ContentType getOrDefault(HttpEntity entity) throws ParseException, UnsupportedCharsetException;
    
    public String getMimeType();
    public Charset getCharset();
    public String getParameter(String name);
}

Utility class for handling HTTP content types.

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    ContentType contentType = ContentType.get(entity);
    
    if (contentType != null) {
        String mimeType = contentType.getMimeType();
        Charset charset = contentType.getCharset();
        
        if (ContentType.APPLICATION_JSON.getMimeType().equals(mimeType)) {
            String json = EntityUtils.toString(entity, charset);
            // Process JSON response
        }
    }
}

Header Processing

Header Interface

public interface Header {
    String getName();
    String getValue();
    HeaderElement[] getElements() throws ParseException;
}

Interface representing an HTTP header.

Working with Response Headers

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    // Get all headers
    Header[] allHeaders = response.getAllHeaders();
    
    // Get specific header
    Header contentType = response.getFirstHeader("Content-Type");
    if (contentType != null) {
        System.out.println("Content-Type: " + contentType.getValue());
    }
    
    // Get multiple headers with same name
    Header[] setCookieHeaders = response.getHeaders("Set-Cookie");
    for (Header header : setCookieHeaders) {
        System.out.println("Set-Cookie: " + header.getValue());
    }
    
    // Check if header exists
    boolean hasLocation = response.containsHeader("Location");
}

Error Handling

Exception Handling

public class HttpResponseException extends ClientProtocolException {
    public HttpResponseException(int statusCode, String reasonPhrase);
    public int getStatusCode();
    public String getReasonPhrase();
}

Exception thrown for HTTP error responses.

Complete Error Handling Example

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    
    if (statusCode >= 200 && statusCode < 300) {
        // Success - process response
        HttpEntity entity = response.getEntity();
        String responseBody = EntityUtils.toString(entity);
        return responseBody;
        
    } else if (statusCode >= 400 && statusCode < 500) {
        // Client error
        throw new ClientProtocolException("Client error: " + statusCode + " " + statusLine.getReasonPhrase());
        
    } else if (statusCode >= 500) {
        // Server error
        throw new ClientProtocolException("Server error: " + statusCode + " " + statusLine.getReasonPhrase());
        
    } else {
        // Unexpected status
        throw new ClientProtocolException("Unexpected status: " + statusCode);
    }
    
} catch (IOException e) {
    // Handle IO exceptions
    throw new RuntimeException("Request failed", e);
}

Streaming Response Processing

Processing Large Responses

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    
    if (entity != null) {
        try (InputStream inputStream = entity.getContent();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                // Process line by line for large responses
                processLine(line);
            }
        }
    }
}

Downloading Files

HttpGet httpGet = new HttpGet("https://example.com/largefile.zip");

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    
    if (entity != null) {
        try (InputStream inputStream = entity.getContent();
             FileOutputStream outputStream = new FileOutputStream("downloaded-file.zip")) {
            
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}

Response Interceptors

HttpResponseInterceptor

public interface HttpResponseInterceptor {
    void process(HttpResponse response, HttpContext context) throws HttpException, IOException;
}

Interface for intercepting and processing HTTP responses.

HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
    @Override
    public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
        // Log response details
        StatusLine statusLine = response.getStatusLine();
        System.out.println("Response: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        
        // Add custom processing
        Header serverHeader = response.getFirstHeader("Server");
        if (serverHeader != null) {
            System.out.println("Server: " + serverHeader.getValue());
        }
    }
};

CloseableHttpClient httpClient = HttpClients.custom()
    .addInterceptorLast(responseInterceptor)
    .build();

Types

ProtocolVersion

public class ProtocolVersion implements Serializable, Cloneable {
    public static final String HTTP = "HTTP";
    
    public ProtocolVersion(String protocol, int major, int minor);
    public final String getProtocol();
    public final int getMajor();
    public final int getMinor();
    public ProtocolVersion forVersion(int major, int minor);
}

Represents HTTP protocol version information.

Locale Support

public interface HttpResponse extends HttpMessage {
    Locale getLocale();
    void setLocale(Locale loc);
}

HTTP responses support locale information for internationalization.

Resource Management Utilities

HttpClientUtils

public final class HttpClientUtils {
    public static void closeQuietly(HttpResponse response);
    public static void closeQuietly(CloseableHttpResponse response);
    public static void closeQuietly(HttpClient httpClient);
}

Utility methods for safely closing HTTP resources without throwing exceptions.

CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;

try {
    HttpGet httpGet = new HttpGet("https://api.example.com");
    response = httpClient.execute(httpGet);
    
    // Process response
    String responseBody = EntityUtils.toString(response.getEntity());
    
} catch (IOException e) {
    // Handle exception
} finally {
    // Safe cleanup
    HttpClientUtils.closeQuietly(response);
    HttpClientUtils.closeQuietly(httpClient);
}

Install with Tessl CLI

npx tessl i tessl/maven-org-apache-httpcomponents--httpclient

docs

authentication.md

client-configuration.md

connection-management.md

cookie-management.md

http-methods.md

index.md

response-handling.md

tile.json