HttpResponse.BodyHandler (Java SE 10 & JDK 10 )
Keywords: jdk.incubator.http.HttpResponse.BodyHandler interface

Module jdk.incubator.httpclient
Package jdk.incubator.http

## Interface HttpResponse.BodyHandler<T>

- Type Parameters:
    `T` - the response body type
  Enclosing class:
    HttpResponse<T>
  Functional Interface:
    This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

      @FunctionalInterface
      public static interface HttpResponse.BodyHandler<T>

  A handler for response bodies.
  Incubating Feature. Will be removed in a future release.

  This is a function that takes two parameters: the response status code, and the response headers, and which returns a HttpResponse.BodySubscriber. The function is always called just before the response body is read. Its implementation may examine the status code or headers and must decide, whether to accept the response body or discard it, and if accepting it, exactly how to handle it.

  Some pre-defined implementations which do not utilize the status code or headers (meaning the body is always accepted) are defined:

  - `asByteArray()`
  - `asByteArrayConsumer(Consumer)`
  - `asString(Charset)`
  - `asFile(Path,OpenOption...)`
  - `asFileDownload(Path,OpenOption...)`
  - `asInputStream()`
  - `discard(Object)`
  - `buffering(BodyHandler,int)`

  These implementations return the equivalent `HttpResponse.BodySubscriber`. Alternatively, the handler can be used to examine the status code or headers and return different body subscribers as appropriate.

  Examples of handler usage

  The first example uses one of the predefined handler functions which ignores the response headers and status, and always process the response body in the same way.

            HttpResponse<Path> resp = HttpRequest
                    .create(URI.create("http://www.foo.com"))
                    .GET()
                    .response(BodyHandler.asFile(Paths.get("/tmp/f")));

  Note, that even though these pre-defined handlers ignore the status code and headers, this information is still accessible from the `HttpResponse` when it is returned.

  In the second example, the function returns a different subscriber depending on the status code.

            HttpResponse<Path> resp1 = HttpRequest
                    .create(URI.create("http://www.foo.com"))
                    .GET()
                    .response(
                        (status, headers) -> status == 200
                            ? BodySubscriber.asFile(Paths.get("/tmp/f"))
                            : BodySubscriber.discard(Paths.get("/NULL")));

- - ### Method Summary

    All Methods Static Methods Instance Methods Abstract Methods
    Modifier and Type | Method | Description
    --- | --- | ---
    `HttpResponse.BodySubscriber<T>` | `apply​(int statusCode, HttpHeaders responseHeaders)` | Returns a `BodySubscriber` considering the given response status code and headers.
    `static HttpResponse.BodyHandler<byte[]>` | `asByteArray()` | Returns a `BodyHandler<byte[]>` that returns a `BodySubscriber`<`byte[]`> obtained from `BodySubscriber.asByteArray()`.
    `static HttpResponse.BodyHandler<Void>` | `asByteArrayConsumer​(Consumer<Optional<byte[]>> consumer)` | Returns a `BodyHandler<Void>` that returns a `BodySubscriber``<Void>` obtained from `BodySubscriber.asByteArrayConsumer(Consumer)`.
    `static HttpResponse.BodyHandler<Path>` | `asFile​(Path file)` | Returns a `BodyHandler<Path>` that returns a `BodySubscriber``<Path>` obtained from `BodySubscriber.asFile(Path)`.
    `static HttpResponse.BodyHandler<Path>` | `asFile​(Path file, OpenOption... openOptions)` | Returns a `BodyHandler<Path>` that returns a `BodySubscriber``<Path>` obtained from `BodySubscriber.asFile(Path,OpenOption...)`.
    `static HttpResponse.BodyHandler<Path>` | `asFileDownload​(Path directory, OpenOption... openOptions)` | Returns a `BodyHandler<Path>` that returns a `BodySubscriber`<`Path`> where the download directory is specified, but the filename is obtained from the `Content-Disposition` response header.
    `static HttpResponse.BodyHandler<InputStream>` | `asInputStream()` | Returns a `BodyHandler<InputStream>` that returns a `BodySubscriber``<InputStream>` obtained from `BodySubscriber.asInputStream`.
    `static HttpResponse.BodyHandler<String>` | `asString()` | Returns a `BodyHandler<String>` that returns a `BodySubscriber``<String>` obtained from `BodySubscriber.asString(Charset)`.
    `static HttpResponse.BodyHandler<String>` | `asString​(Charset charset)` | Returns a `BodyHandler<String>` that returns a `BodySubscriber``<String>` obtained from `BodySubscriber.asString(Charset)`.
    `static <T> HttpResponse.BodyHandler<T>` | `buffering​(HttpResponse.BodyHandler<T> downstreamHandler, int bufferSize)` | Returns a `BodyHandler` which, when invoked, returns a buffering BodySubscriber that buffers data before delivering it to the downstream subscriber.
    `static <U> HttpResponse.BodyHandler<U>` | `discard​(U value)` | Returns a response body handler which discards the response body and uses the given value as a replacement for it.
    `static HttpResponse.BodyHandler<Void>` | `fromSubscriber​(Flow.Subscriber<? super List<ByteBuffer>> subscriber)` | Returns a response body handler that returns a `BodySubscriber``<Void>` obtained from HttpResponse.BodySubscriber.fromSubscriber(Subscriber), with the given `subscriber`.
    `static <S extends Flow.Subscriber<? super List<ByteBuffer>>,T> HttpResponse.BodyHandler<T>` | `fromSubscriber​(S subscriber, Function<S,T> finisher)` | Returns a response body handler that returns a `BodySubscriber``<T>` obtained from `HttpResponse.BodySubscriber.fromSubscriber(Subscriber, Function)`, with the given `subscriber` and `finisher` function.

- - ### Method Detail

    - #### apply

          HttpResponse.BodySubscriber<T> apply​(int statusCode,
                                               HttpHeaders responseHeaders)

      Returns a `BodySubscriber` considering the given response status code and headers. This method is always called before the body is read and its implementation can decide to keep the body and store it somewhere, or else discard it by returning the `BodySubscriber` returned from `discard`.
      Parameters:
        `statusCode` - the HTTP status code received
        `responseHeaders` - the response headers received
      Returns:
        a body subscriber

    - #### fromSubscriber

          static HttpResponse.BodyHandler<Void> fromSubscriber​(Flow.Subscriber<? super List<ByteBuffer>> subscriber)

      Returns a response body handler that returns a `BodySubscriber``<Void>` obtained from HttpResponse.BodySubscriber.fromSubscriber(Subscriber), with the given `subscriber`.

      The response body is not available through this, or the `HttpResponse` API, but instead all response body is forwarded to the given `subscriber`, which should make it available, if appropriate, through some other mechanism, e.g. an entry in a database, etc.

      API Note:
        This method can be used as an adapter between `BodySubscriber` and `Flow.Subscriber`.

        For example:

              TextSubscriber subscriber = new TextSubscriber();
              HttpResponse<Void> response = client.sendAsync(request,
                  BodyHandler.fromSubscriber(subscriber)).join();
              System.out.println(response.statusCode());

      Parameters:
        `subscriber` - the subscriber
      Returns:
        a response body handler

    - #### fromSubscriber

          static <S extends Flow.Subscriber<? super List<ByteBuffer>>,T> HttpResponse.BodyHandler<T> fromSubscriber​(S subscriber,
                                                                                                                    Function<S,T> finisher)

      Returns a response body handler that returns a `BodySubscriber``<T>` obtained from `HttpResponse.BodySubscriber.fromSubscriber(Subscriber, Function)`, with the given `subscriber` and `finisher` function.

      The given `finisher` function is applied after the given subscriber's `onComplete` has been invoked. The `finisher` function is invoked with the given subscriber, and returns a value that is set as the response's body.

      API Note:
        This method can be used as an adapter between `BodySubscriber` and `Flow.Subscriber`.

        For example:

             TextSubscriber subscriber = ...;  // accumulates bytes and transforms them into a String
             HttpResponse<String> response = client.sendAsync(request,
                 BodyHandler.fromSubscriber(subscriber, TextSubscriber::getTextResult)).join();
             String text = response.body();

      Type Parameters:
        `S` - the type of the Subscriber
        `T` - the type of the response body
      Parameters:
        `subscriber` - the subscriber
        `finisher` - a function to be applied after the subscriber has completed
      Returns:
        a response body handler

    - #### discard

          static <U> HttpResponse.BodyHandler<U> discard​(U value)

      Returns a response body handler which discards the response body and uses the given value as a replacement for it.
      Type Parameters:
        `U` - the response body type
      Parameters:
        `value` - the value of U to return as the body, may be `null`
      Returns:
        a response body handler

    - #### asString

          static HttpResponse.BodyHandler<String> asString​(Charset charset)

      Returns a `BodyHandler<String>` that returns a `BodySubscriber``<String>` obtained from `BodySubscriber.asString(Charset)`. The body is decoded using the given character set.
      Parameters:
        `charset` - the character set to convert the body with
      Returns:
        a response body handler

    - #### asFile

          static HttpResponse.BodyHandler<Path> asFile​(Path file,
                                                       OpenOption... openOptions)

      Returns a `BodyHandler<Path>` that returns a `BodySubscriber``<Path>` obtained from `BodySubscriber.asFile(Path,OpenOption...)`.

      When the `HttpResponse` object is returned, the body has been completely written to the file, and `HttpResponse.body()` returns a reference to its `Path`.

      Parameters:
        `file` - the filename to store the body in
        `openOptions` - any options to use when opening/creating the file
      Returns:
        a response body handler
      Throws:
        `SecurityException` - If a security manager has been installed and it denies `write access` to the file. The `checkDelete` method is invoked to check delete access if the file is opened with the `DELETE_ON_CLOSE` option.

    - #### asFile

          static HttpResponse.BodyHandler<Path> asFile​(Path file)

      Returns a `BodyHandler<Path>` that returns a `BodySubscriber``<Path>` obtained from `BodySubscriber.asFile(Path)`.

      When the `HttpResponse` object is returned, the body has been completely written to the file, and `HttpResponse.body()` returns a reference to its `Path`.

      Parameters:
        `file` - the file to store the body in
      Returns:
        a response body handler
      Throws:
        `SecurityException` - if a security manager has been installed and it denies `write access` to the file

    - #### asFileDownload

          static HttpResponse.BodyHandler<Path> asFileDownload​(Path directory,
                                                               OpenOption... openOptions)

      Returns a `BodyHandler<Path>` that returns a `BodySubscriber`<`Path`> where the download directory is specified, but the filename is obtained from the `Content-Disposition` response header. The `Content-Disposition` header must specify the attachment type and must also contain a filename parameter. If the filename specifies multiple path components only the final component is used as the filename (with the given directory name).

      When the `HttpResponse` object is returned, the body has been completely written to the file and `HttpResponse.body()` returns a `Path` object for the file. The returned `Path` is the combination of the supplied directory name and the file name supplied by the server. If the destination directory does not exist or cannot be written to, then the response will fail with an `IOException`.

      Parameters:
        `directory` - the directory to store the file in
        `openOptions` - open options
      Returns:
        a response body handler
      Throws:
        `SecurityException` - If a security manager has been installed and it denies `write access` to the file. The `checkDelete` method is invoked to check delete access if the file is opened with the `DELETE_ON_CLOSE` option.

    - #### asInputStream

          static HttpResponse.BodyHandler<InputStream> asInputStream()

      Returns a `BodyHandler<InputStream>` that returns a `BodySubscriber``<InputStream>` obtained from `BodySubscriber.asInputStream`.

      When the `HttpResponse` object is returned, the response headers will have been completely read, but the body may not have been fully received yet. The `HttpResponse.body()` method returns an `InputStream` from which the body can be read as it is received.

      API Note:
        See `HttpResponse.BodySubscriber.asInputStream()` for more information.
      Returns:
        a response body handler

    - #### asByteArrayConsumer

          static HttpResponse.BodyHandler<Void> asByteArrayConsumer​(Consumer<Optional<byte[]>> consumer)

      Returns a `BodyHandler<Void>` that returns a `BodySubscriber``<Void>` obtained from `BodySubscriber.asByteArrayConsumer(Consumer)`.

      When the `HttpResponse` object is returned, the body has been completely written to the consumer.

      Parameters:
        `consumer` - a Consumer to accept the response body
      Returns:
        a response body handler

    - #### asByteArray

          static HttpResponse.BodyHandler<byte[]> asByteArray()

      Returns a `BodyHandler<byte[]>` that returns a `BodySubscriber`<`byte[]`> obtained from `BodySubscriber.asByteArray()`.

      When the `HttpResponse` object is returned, the body has been completely written to the byte array.

      Returns:
        a response body handler

    - #### asString

          static HttpResponse.BodyHandler<String> asString()

      Returns a `BodyHandler<String>` that returns a `BodySubscriber``<String>` obtained from `BodySubscriber.asString(Charset)`. The body is decoded using the character set specified in the `Content-encoding` response header. If there is no such header, or the character set is not supported, then `UTF_8` is used.

      When the `HttpResponse` object is returned, the body has been completely written to the string.

      Returns:
        a response body handler

    - #### buffering

          static <T> HttpResponse.BodyHandler<T> buffering​(HttpResponse.BodyHandler<T> downstreamHandler,
                                                           int bufferSize)

      Returns a `BodyHandler` which, when invoked, returns a buffering BodySubscriber that buffers data before delivering it to the downstream subscriber. These `BodySubscriber` instances are created by calling BodySubscriber.buffering with a subscriber obtained from the given downstream handler and the `bufferSize` parameter.
      Parameters:
        `downstreamHandler` - the downstream handler
        `bufferSize` - the buffer size parameter passed to BodySubscriber.buffering
      Returns:
        a body handler
      Throws:
        `IllegalArgumentException` - if `bufferSize <= 0`