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