Class HTTPResponse
This class provides a structured representation of an HTTP response that can be sent to clients. It manages all components of an HTTP response including the status line, headers, and message body, and provides methods to construct and transmit the response according to HTTP/1.1 specifications.
Key features:
- Flexible header management with support for multi-value headers
- Automatic Content-Length and Content-Type header setting when body is provided
- UTF-8 encoding for text headers and arbitrary binary body support
- Track whether response has been sent to prevent duplicate transmission
- Thread-safe transmission to socket output streams
Response structure (HTTP/1.1 format):
HTTP/1.1 {statusCode} {statusMessage}
{Header-Name}: {Header-Value}
...
{Body}
Usage example:
HTTPResponse response = new HTTPResponse(200, "OK");
response.setHeader("Content-Type", "application/json");
response.setBody("{\"status\":\"success\"}".getBytes(), "application/json");
response.send(clientSocket);
Thread-safety: This class is not thread-safe. A single HTTPResponse instance should not be modified concurrently by multiple threads. However, different threads can safely create and send their own HTTPResponse instances.
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionHTTPResponse(int statusCode, String statusMessage) Constructs an HTTPResponse object with the specified status code and status message. -
Method Summary
Modifier and TypeMethodDescriptionbooleanisSended()Checks whether this response has been sent to a client.voidSends the HTTP response to the client through the provided socket.voidSets the body of the HTTP response and automatically updates the Content-Length and Content-Type headers.voidSets a header for the HTTP response.
-
Constructor Details
-
HTTPResponse
Constructs an HTTPResponse object with the specified status code and status message.This constructor initializes the response with the given status information. Headers and body can be added after construction using
setHeader(String, String)andsetBody(byte[], String)methods.The status code and message should correspond to standard HTTP status codes and their conventional messages, though any values are technically allowed.
- Parameters:
statusCode- The HTTP status code (e.g., 200, 404, 500). Should be a valid HTTP status code in the range 100-599.statusMessage- The HTTP status message (e.g., "OK", "Not Found", "Internal Server Error"). Should be a brief, human-readable description. Must not be null.
-
-
Method Details
-
setHeader
Sets a header for the HTTP response.If the header already exists, the new value is appended to the existing values, allowing for multi-value headers (e.g., multiple Set-Cookie headers). If the header does not exist, it is created with the provided value.
Header names are case-insensitive according to HTTP specification, but this implementation preserves the case as provided. Common headers include:
- Content-Type - MIME type of the response body
- Content-Length - Size of the response body in bytes
- Cache-Control - Caching directives
- Set-Cookie - Set cookies in the client browser
- Location - Redirect target URL
Note: When using
setBody(byte[], String), Content-Length and Content-Type headers are set automatically.- Parameters:
key- The name of the header (e.g., "Content-Type", "Cache-Control"). Must not be null.value- The value of the header (e.g., "application/json", "no-cache"). Must not be null.
-
setBody
Sets the body of the HTTP response and automatically updates the Content-Length and Content-Type headers.This method performs three operations:
- Stores the provided byte array as the response body
- Sets the Content-Length header to the exact size of the body
- Sets the Content-Type header to the specified MIME type
The Content-Length header is critical for HTTP/1.1 as it allows clients to know when the response is complete. The Content-Type header informs clients how to interpret the body content.
Common content types:
- text/html - HTML documents
- text/plain - Plain text
- application/json - JSON data
- application/xml - XML data
- image/jpeg, image/png - Image files
- application/octet-stream - Binary data
- Parameters:
body- The body of the response as a byte array. Must not be null. Use an empty array for responses with no content.contentType- The MIME type of the body content (e.g., "text/html", "application/json"). Should include charset if applicable (e.g., "text/html; charset=utf-8"). Must not be null.
-
send
Sends the HTTP response to the client through the provided socket.This method constructs and transmits the complete HTTP response according to the HTTP/1.1 specification. It performs the following operations in sequence:
- Writes the status line: "HTTP/1.1 {statusCode} {statusMessage}\\r\\n"
- Writes all headers in the format: "{Header-Name}: {Header-Value}\\r\\n"
- Writes a blank line (\\r\\n) to separate headers from body
- Writes the body bytes if present
- Flushes all output to ensure delivery
- Sets the
sendedflag to true
Headers are written using UTF-8 encoding, which is the standard for HTTP headers. The body is written as raw bytes, preserving any encoding specified in the Content-Type header.
After calling this method, the response is considered sent and the
isSended()method will return true. This can be used to prevent duplicate transmission.Note: This method does not close the socket, allowing for persistent connections (HTTP keep-alive). The socket should be closed by the caller when appropriate.
- Parameters:
socket- The client socket to send the response to. Must not be null and should have an open output stream.- Throws:
Exception- If an I/O error occurs while writing to the socket output stream. This could indicate network issues, client disconnection, or socket closure.
-
isSended
public boolean isSended()Checks whether this response has been sent to a client.This method returns the status of the
sendedflag, which is set to true aftersend(Socket)completes successfully. This can be used to:- Prevent accidental duplicate transmission of the same response
- Determine if a handler has already sent the response directly to the socket
- Track response lifecycle for logging or debugging purposes
Some handlers (e.g., SSE handlers) may send responses directly to the socket and set this flag to indicate that the framework should not attempt to send the response again.
- Returns:
trueif the response has been sent,falseotherwise.
-