HttpExchange (Java SE 26 & JDK 26)
Description: declaration: module: jdk.httpserver, package: com.sun.net.httpserver, class: HttpExchange
Keywords: com.sun.net.httpserver.HttpExchange class

# Class HttpExchange

java.lang.Object
com.sun.net.httpserver.HttpExchange

All Implemented Interfaces:
  `Request, AutoCloseable`

Direct Known Subclasses:
  `HttpsExchange`

public abstract class HttpExchange extends Object implements AutoCloseable, Request
This class encapsulates a HTTP request received and a response to be generated in one exchange. It provides methods for examining the request from the client, and for building and sending the response.

The typical life-cycle of a `HttpExchange` is shown in the sequence below:

1. `getRequestMethod()` to determine the command.
2. `getRequestHeaders()` to examine the request headers (if needed).
3. `getRequestBody()` returns an `InputStream` for reading the request body. After reading the request body, the stream should be closed.
4. `getResponseHeaders()` to set any response headers, except content-length.
5. `sendResponseHeaders(int,long)` to send the response headers. Must be called before next step.
6. `getResponseBody()` to get a `OutputStream` to send the response body. When the response body has been written, the stream must be closed to terminate the exchange.

Terminating exchanges
Exchanges are terminated when both the request `InputStream` and response `OutputStream` are closed. Closing the `OutputStream`, implicitly closes the `InputStream` (if it is not already closed). However, it is recommended to consume all the data from the `InputStream` before closing it. The convenience method `close()` does all of these tasks. Closing an exchange without consuming all of the request body is not an error but may make the underlying TCP connection unusable for following exchanges. The effect of failing to terminate an exchange is undefined, but will typically result in resources failing to be freed/reused.

Since:
  1.6

- ## Field Summary

  Fields
  Modifier and Type
  Field
  Description
  `static final long`
  `RSPBODY_CHUNKED`
  The response body length is unspecified and will be chunk encoded
  `static final long`
  `RSPBODY_EMPTY`
  No response body is being sent with this response

- ## Constructor Summary

  Constructors
  Modifier
  Constructor
  Description
  `protected`
  `HttpExchange()`
  Constructor for subclasses to call.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `abstract void`
  `close()`
  Ends this exchange by doing the following in sequence: close the request `InputStream`, if not already closed.
  `abstract Object`
  `getAttribute(String name)`
  `Filter` modules may store arbitrary objects with `HttpExchange` instances as an out-of-band communication mechanism.
  `abstract HttpContext`
  `getHttpContext()`
  Returns the `HttpContext` for this exchange.
  `abstract InetSocketAddress`
  `getLocalAddress()`
  Returns the local address on which the request was received.
  `abstract HttpPrincipal`
  `getPrincipal()`
  If an authenticator is set on the `HttpContext` that owns this exchange, then this method will return the `HttpPrincipal` that represents the authenticated user for this `HttpExchange`.
  `abstract String`
  `getProtocol()`
  Returns the protocol string from the request in the form protocol/majorVersion.minorVersion.
  `abstract InetSocketAddress`
  `getRemoteAddress()`
  Returns the address of the remote entity invoking this request.
  `abstract InputStream`
  `getRequestBody()`
  Returns a stream from which the request body can be read.
  `abstract Headers`
  `getRequestHeaders()`
  Returns an immutable `Headers` containing the HTTP headers that were included with this request.
  `abstract String`
  `getRequestMethod()`
  Returns the request method.
  `abstract URI`
  `getRequestURI()`
  Returns the request `URI`.
  `abstract OutputStream`
  `getResponseBody()`
  Returns a stream to which the response body must be written.
  `abstract int`
  `getResponseCode()`
  Returns the response code, if it has already been set.
  `abstract Headers`
  `getResponseHeaders()`
  Returns a mutable `Headers` into which the HTTP response headers can be stored and which will be transmitted as part of this response.
  `abstract void`
  `sendResponseHeaders(int rCode, long responseLength)`
  Starts sending the response back to the client using the current set of response headers and the numeric response code as specified in this method.
  `abstract void`
  `setAttribute(String name, Object value)`
  `Filter` modules may store arbitrary objects with `HttpExchange` instances as an out-of-band communication mechanism.
  `abstract void`
  `setStreams(InputStream i, OutputStream o)`
  Used by Filters to wrap either (or both) of this exchange's `InputStream` and `OutputStream`, with the given filtered streams so that subsequent calls to `getRequestBody()` will return the given `InputStream`, and calls to `getResponseBody()` will return the given `OutputStream`.

  ### Methods declared in class Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`
  Modifier and Type
  Method
  Description
  `protected Object`
  `clone()`
  Creates and returns a copy of this object.
  `boolean`
  `equals(Object obj)`
  Indicates whether some other object is "equal to" this one.
  `protected void`
  `finalize()`
  Deprecated, for removal: This API element is subject to removal in a future version.
  Finalization is deprecated and subject to removal in a future release.
  `final Class<?>`
  `getClass()`
  Returns the runtime class of this `Object`.
  `int`
  `hashCode()`
  Returns a hash code value for this object.
  `final void`
  `notify()`
  Wakes up a single thread that is waiting on this object's monitor.
  `final void`
  `notifyAll()`
  Wakes up all threads that are waiting on this object's monitor.
  `String`
  `toString()`
  Returns a string representation of the object.
  `final void`
  `wait()`
  Causes the current thread to wait until it is awakened, typically by being notified or interrupted.
  `final void`
  `wait(long timeoutMillis)`
  Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.
  `final void`
  `wait(long timeoutMillis, int nanos)`
  Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

  ### Methods declared in interface Request

  `with`
  Modifier and Type
  Method
  Description
  `default Request`
  `with(String headerName, List<String> headerValues)`
  Returns an identical `Request` with an additional header.

- ## Field Details

  - ### RSPBODY_EMPTY

    public static final long RSPBODY_EMPTY
    No response body is being sent with this response
    Since:
      26
    See Also:
      - `sendResponseHeaders(int, long)`
      - Constant Field Values

  - ### RSPBODY_CHUNKED

    public static final long RSPBODY_CHUNKED
    The response body length is unspecified and will be chunk encoded
    Since:
      26
    See Also:
      - `sendResponseHeaders(int, long)`
      - Constant Field Values

- ## Constructor Details

  - ### HttpExchange

    protected HttpExchange()
    Constructor for subclasses to call.

- ## Method Details

  - ### getRequestHeaders

    public abstract Headers getRequestHeaders()
    Returns an immutable `Headers` containing the HTTP headers that were included with this request.

    The keys in this `Headers` are the header names, while the values are a `List` of Strings containing each value that was included in the request, in the order they were included. Header fields appearing multiple times are represented as multiple string values.

    The keys in `Headers` are case-insensitive.

    Specified by:
      `getRequestHeaders` in interface `Request`
    Returns:
      a read-only `Headers` which can be used to access request headers.

  - ### getResponseHeaders

    public abstract Headers getResponseHeaders()
    Returns a mutable `Headers` into which the HTTP response headers can be stored and which will be transmitted as part of this response.

    The keys in the `Headers` are the header names, while the values must be a `List` of Strings containing each value that should be included multiple times (in the order that they should be included).

    The keys in `Headers` are case-insensitive.

    Returns:
      a writable `Headers` which can be used to set response headers.

  - ### getRequestURI

    public abstract URI getRequestURI()
    Returns the request `URI`.
    Specified by:
      `getRequestURI` in interface `Request`
    Returns:
      the request `URI`

  - ### getRequestMethod

    public abstract String getRequestMethod()
    Returns the request method.
    Specified by:
      `getRequestMethod` in interface `Request`
    Returns:
      the request method string

  - ### getHttpContext

    public abstract HttpContext getHttpContext()
    Returns the `HttpContext` for this exchange.
    Returns:
      the `HttpContext`

  - ### close

    public abstract void close()
    Ends this exchange by doing the following in sequence:
    1. close the request `InputStream`, if not already closed.
    2. close the response `OutputStream`, if not already closed.
    Specified by:
      `close` in interface `AutoCloseable`

  - ### getRequestBody

    public abstract InputStream getRequestBody()
    Returns a stream from which the request body can be read. Multiple calls to this method will return the same stream. It is recommended that applications should consume (read) all of the data from this stream before closing it. If a stream is closed before all data has been read, then the `InputStream.close()` call will read and discard remaining data (up to an implementation specific number of bytes).
    Returns:
      the stream from which the request body can be read

  - ### getResponseBody

    public abstract OutputStream getResponseBody()
    Returns a stream to which the response body must be written. `sendResponseHeaders(int,long)`) must be called prior to calling this method. Multiple calls to this method (for the same exchange) will return the same stream. In order to correctly terminate each exchange, the output stream must be closed, even if no response body is being sent.

    Closing this stream implicitly closes the `InputStream` returned from `getRequestBody()` (if it is not already closed).

    If the call to `sendResponseHeaders(int, long)` specified a fixed response body length, then the exact number of bytes specified in that call must be written to this stream. If too many bytes are written, then the write method of `OutputStream` will throw an `IOException`. If too few bytes are written then the stream `OutputStream.close()` will throw an `IOException`. In both cases, the exchange is aborted and the underlying TCP connection closed.

    Returns:
      the stream to which the response body is written

  - ### sendResponseHeaders

    public abstract void sendResponseHeaders(int rCode, long responseLength) throws IOException
    Starts sending the response back to the client using the current set of response headers and the numeric response code as specified in this method. The response body length is also specified as follows. If the response length parameter is greater than `zero`, this specifies an exact number of bytes to send and the application must send that exact amount of data. If the response length parameter has the value `RSPBODY_CHUNKED` (zero) then the response body uses chunked transfer encoding and an arbitrary amount of data may be sent. The application terminates the response body by closing the `OutputStream`. If response length has the value `RSPBODY_EMPTY` then no response body is being sent.

    If the content-length response header has not already been set then this is set to the appropriate value depending on the response length parameter.

    This method must be called prior to calling `getResponseBody()`.

    API Note:
      If a response body is to be sent from a byte array and the length of the array is used as the responseLength parameter, then note the behavior in the case when the array is empty. In that case, the responseLength will be zero which is the value of `RSPBODY_CHUNKED` resulting in a zero length, but chunked encoded response body. While this is not incorrect, it may be preferable to check for an empty array and set responseLength to `RSPBODY_EMPTY` instead. Also, when sending a chunked encoded response body, whatever length, the output stream must be explicitly closed by the handler.
    Implementation Note:
      This implementation allows the caller to instruct the server to force a connection close after the exchange terminates, by supplying a `Connection: close` header to the response headers before `sendResponseHeaders` is called.
    Parameters:
      `rCode` - the response code to send
      `responseLength` - if > 0, specifies a fixed response body length and that exact number of bytes must be written to the stream acquired from `getResponseCode()` If equal to `RSPBODY_CHUNKED`, then chunked encoding is used, and an arbitrary number of bytes may be written. If equal to `RSPBODY_EMPTY`, then no response body length is specified and no response body may be written. Any value <= -1 is treated the same as `RSPBODY_EMPTY`.
    Throws:
      `IOException` - if the response headers have already been sent or an I/O error occurs
    See Also:
      - `getResponseBody()`

  - ### getRemoteAddress

    public abstract InetSocketAddress getRemoteAddress()
    Returns the address of the remote entity invoking this request.
    Returns:
      the `InetSocketAddress` of the caller

  - ### getResponseCode

    public abstract int getResponseCode()
    Returns the response code, if it has already been set.
    Returns:
      the response code, if available. `-1` if not available yet.

  - ### getLocalAddress

    public abstract InetSocketAddress getLocalAddress()
    Returns the local address on which the request was received.
    Returns:
      the `InetSocketAddress` of the local interface

  - ### getProtocol

    public abstract String getProtocol()
    Returns the protocol string from the request in the form protocol/majorVersion.minorVersion. For example, "`HTTP/1.1`".
    Returns:
      the protocol string from the request

  - ### getAttribute

    public abstract Object getAttribute(String name)
    `Filter` modules may store arbitrary objects with `HttpExchange` instances as an out-of-band communication mechanism. Other filters or the exchange handler may then access these objects.

    Each `Filter` class will document the attributes which they make available.

    Parameters:
      `name` - the name of the attribute to retrieve
    Returns:
      the attribute object, or `null` if it does not exist
    Throws:
      `NullPointerException` - if name is `null`

  - ### setAttribute

    public abstract void setAttribute(String name, Object value)
    `Filter` modules may store arbitrary objects with `HttpExchange` instances as an out-of-band communication mechanism. Other filters or the exchange handler may then access these objects.

    Each `Filter` class will document the attributes which they make available.

    Parameters:
      `name` - the name to associate with the attribute value
      `value` - the object to store as the attribute value. `null` value is permitted.
    Throws:
      `NullPointerException` - if name is `null`

  - ### setStreams

    public abstract void setStreams(InputStream i, OutputStream o)
    Used by Filters to wrap either (or both) of this exchange's `InputStream` and `OutputStream`, with the given filtered streams so that subsequent calls to `getRequestBody()` will return the given `InputStream`, and calls to `getResponseBody()` will return the given `OutputStream`. The streams provided to this call must wrap the original streams, and may be (but are not required to be) sub-classes of `FilterInputStream` and `FilterOutputStream`.
    Parameters:
      `i` - the filtered input stream to set as this object's `Inputstream`, or `null` if no change
      `o` - the filtered output stream to set as this object's `Outputstream`, or `null` if no change

  - ### getPrincipal

    public abstract HttpPrincipal getPrincipal()
    If an authenticator is set on the `HttpContext` that owns this exchange, then this method will return the `HttpPrincipal` that represents the authenticated user for this `HttpExchange`.
    Returns:
      the `HttpPrincipal`, or `null` if no authenticator is set