Class HttpExchanges

java.lang.Object
dev.mccue.jdk.httpserver.HttpExchanges

public final class HttpExchanges extends Object
Helpers for working with an HttpExchange.

In an ideal world, these would be instance methods on the HttpExchange class itself. If that ever happens this library will be obsolete in a good way.

  • Method Details

    • sendResponseHeaders

      public static void sendResponseHeaders(HttpExchange exchange, int rCode, ResponseLength 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 is known, this specifies an exact number of bytes to send and the application must send that exact amount of data. If the response length is unknown, then chunked transfer encoding is used and an arbitrary amount of data may be sent. The application terminates the response body by closing the OutputStream.

      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 HttpExchange.getResponseBody().

      Parameters:
      exchange - the HttpExchange to use
      rCode - the response code to send
      responseLength - a ResponseLength which specifies the amount of bytes that will eventually be written to the response body.
      Throws:
      IOException - if the response headers have already been sent or an I/O error occurs
      See Also:
    • sendResponse

      public static void sendResponse(HttpExchange exchange, int rCode, Body body) throws IOException
      Sends a response to the client.

      If no Content-Type header has been specified, will use the one returned by Body.defaultContentType().

      Calling this will close the InputStream returned by HttpExchange.getResponseBody(), which implicitly closes the InputStream returned from HttpExchange.getRequestBody() (if it is not already closed).

      Parameters:
      exchange - the HttpExchange to use
      rCode - the response code to send
      body - the Body to send
      Throws:
      IOException - if the response headers have already been sent or an I/O error occurs