HttpResponse<T>public static class HttpResponse.BodySubscribers extends Object
BodySubscriber that implement various useful subscribers, such as converting the response body bytes into a String, or streaming the bytes to a file. The following are examples of using the predefined body subscribers to convert a flow of response body data into common high-level Java objects:
// Streams the response body to a File
HttpResponse<Path> response = client
  .send(request, responseInfo -> BodySubscribers.ofFile(Paths.get("example.html"));// Accumulates the response body and returns it as a byte[]
HttpResponse<byte[]> response = client
  .send(request, responseInfo -> BodySubscribers.ofByteArray());// Discards the response body
HttpResponse<Void> response = client
  .send(request, responseInfo -> BodySubscribers.discarding());// Accumulates the response body as a String then maps it to its bytes
HttpResponse<byte[]> response = client
  .send(request, responseInfo ->
     BodySubscribers.mapping(BodySubscribers.ofString(UTF_8), String::getBytes));| Modifier and Type | Method | Description | 
|---|---|---|
| static <T> HttpResponse.BodySubscriber | buffering | Returns a  BodySubscriberwhich buffers data before delivering it to the given downstream subscriber. | 
| static HttpResponse.BodySubscriber | discarding() | Returns a response subscriber which discards the response body. | 
| static HttpResponse.BodySubscriber | fromLineSubscriber | Returns a body subscriber that forwards all response body to the given  Flow.Subscriber, line by line. | 
| static <S extends Flow.Subscriber<? super String>, | fromLineSubscriber | Returns a body subscriber that forwards all response body to the given  Flow.Subscriber, line by line. | 
| static HttpResponse.BodySubscriber | fromSubscriber | Returns a body subscriber that forwards all response body to the given  Flow.Subscriber. | 
| static <S extends Flow.Subscriber<? super List<ByteBuffer>>, | fromSubscriber | Returns a body subscriber that forwards all response body to the given  Flow.Subscriber. | 
| static <T, | mapping | Returns a  BodySubscriberwhose response body value is that of the result of applying the given function to the body object of the givenupstreamBodySubscriber. | 
| static HttpResponse.BodySubscriber | ofByteArray() | Returns a  BodySubscriberwhich stores the response body as a byte array. | 
| static HttpResponse.BodySubscriber | ofByteArrayConsumer | Returns a  BodySubscriberwhich provides the incoming body data to the provided Consumer ofOptional<byte[]>. | 
| static HttpResponse.BodySubscriber | ofFile | Returns a  BodySubscriberwhich stores the response body in a file opened with the given name. | 
| static HttpResponse.BodySubscriber | ofFile | Returns a  BodySubscriberwhich stores the response body in a file opened with the given options and name. | 
| static HttpResponse.BodySubscriber | ofInputStream() | Returns a  BodySubscriberwhich streams the response body as anInputStream. | 
| static HttpResponse.BodySubscriber | ofLines | Returns a  BodySubscriberwhich streams the response body as aStream<String>, where each string in the stream corresponds to a line as defined byBufferedReader.lines(). | 
| static HttpResponse.BodySubscriber | ofPublisher() | Returns a response subscriber which publishes the response body through a  Publisher<List<ByteBuffer>>. | 
| static HttpResponse.BodySubscriber | ofString | Returns a body subscriber which stores the response body as a  
 Stringconverted using the givenCharset. | 
| static <U> HttpResponse.BodySubscriber | replacing | Returns a response subscriber which discards the response body. | 
public static HttpResponse.BodySubscriber<Void> fromSubscriber(Flow.Subscriber<? super List<ByteBuffer>> subscriber)
Flow.Subscriber. The completion stage of the returned body subscriber completes after one of the given subscribers onComplete or onError has been invoked.
 BodySubscriber and Flow.Subscriber.subscriber - the subscriberpublic static <S extends Flow.Subscriber<? super List<ByteBuffer>>, T> HttpResponse.BodySubscriber<T> fromSubscriber(S subscriber, Function<? super S,? extends T> finisher)
Flow.Subscriber. The completion stage of the returned body subscriber completes after one of the given subscribers onComplete or onError has been invoked.  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.
 BodySubscriber and Flow.Subscriber.S - the type of the SubscriberT - the type of the response bodysubscriber - the subscriberfinisher - a function to be applied after the subscriber has completedpublic static HttpResponse.BodySubscriber<Void> fromLineSubscriber(Flow.Subscriber<? super String> subscriber)
Flow.Subscriber, line by line. The completion stage of the returned body subscriber completes after one of the given subscribers onComplete or onError has been invoked. Bytes are decoded using the UTF-8 charset, and lines are delimited in the manner of BufferedReader.readLine().
 BodySubscriber and Flow.Subscriber.fromLineSubscriber(subscriber, s -> null, StandardCharsets.UTF_8, null)subscriber - the subscriberpublic static <S extends Flow.Subscriber<? super String>, T> HttpResponse.BodySubscriber<T> fromLineSubscriber(S subscriber, Function<? super S,? extends T> finisher, Charset charset, String lineSeparator)
Flow.Subscriber, line by line. The completion stage of the returned body subscriber completes after one of the given subscribers onComplete or onError has been invoked.  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.
 BodySubscriber and Flow.Subscriber.S - the type of the SubscriberT - the type of the response bodysubscriber - the subscriberfinisher - a function to be applied after the subscriber has completedcharset - a Charset to decode the byteslineSeparator - an optional line separator: can be null, in which case lines will be delimited in the manner of BufferedReader.readLine().IllegalArgumentException - if the supplied lineSeparator is the empty stringpublic static HttpResponse.BodySubscriber<String> ofString(Charset charset)
 String converted using the given Charset.  The HttpResponse using this subscriber is available after the entire response has been read.
charset - the character set to convert the String withpublic static HttpResponse.BodySubscriber<byte[]> ofByteArray()
BodySubscriber which stores the response body as a byte array.  The HttpResponse using this subscriber is available after the entire response has been read.
public static HttpResponse.BodySubscriber<Path> ofFile(Path file, OpenOption... openOptions)
BodySubscriber which stores the response body in a file opened with the given options and name. The file will be opened with the given options using FileChannel.open just before the body is read. Any exception thrown will be returned or thrown from HttpClient::send or HttpClient::sendAsync as appropriate.  The HttpResponse using this subscriber is available after the entire response has been read. 
 In the case of the default file system provider, security manager permission checks are performed in this factory method, when the BodySubscriber is created. Otherwise, permission checks may be performed asynchronously against the caller's context at file access time. Care must be taken that the BodySubscriber is not shared with untrusted code.
file - the file to store the body inopenOptions - the list of options to open the file withIllegalArgumentException - if an invalid set of open options are specifiedSecurityException - in the case of the default file system provider, and a security manager is installed, checkWrite is invoked to check write access to the given filepublic static HttpResponse.BodySubscriber<Path> ofFile(Path file)
BodySubscriber which stores the response body in a file opened with the given name.  Equivalent to: ofFile(file, CREATE, WRITE) 
 In the case of the default file system provider, security manager permission checks are performed in this factory method, when the BodySubscriber is created. Otherwise, permission checks may be performed asynchronously against the caller's context at file access time. Care must be taken that the BodySubscriber is not shared with untrusted code.
file - the file to store the body inSecurityException - in the case of the default file system provider, and a security manager is installed, checkWrite is invoked to check write access to the given filepublic static HttpResponse.BodySubscriber<Void> ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer)
BodySubscriber which provides the incoming body data to the provided Consumer of Optional<byte[]>. Each call to Consumer.accept() will contain a non empty Optional, except for the final invocation after all body data has been read, when the 
 Optional will be empty.  The HttpResponse using this subscriber is available after the entire response has been read.
consumer - a Consumer of byte arrayspublic static HttpResponse.BodySubscriber<InputStream> ofInputStream()
BodySubscriber which streams the response body as an InputStream.  The HttpResponse using this subscriber is available immediately after the response headers have been read, without requiring to wait for the entire body to be processed. The response body can then be read directly from the InputStream.
InputStream.close() if it is unable or unwilling to do so. Calling close before exhausting the stream may cause the underlying HTTP connection to be closed and prevent it from being reused for subsequent operations.read method of the InputStream returned by the default implementation of this method will throw an IOException with the thread interrupt status set if the thread is interrupted while blocking on read. In that case, the request will also be cancelled and the InputStream will be closed.InputStream.public static HttpResponse.BodySubscriber<Stream<String>> ofLines(Charset charset)
BodySubscriber which streams the response body as a Stream<String>, where each string in the stream corresponds to a line as defined by BufferedReader.lines().  The HttpResponse using this subscriber is available immediately after the response headers have been read, without requiring to wait for the entire body to be processed. The response body can then be read directly from the Stream.
BaseStream.close() if it is unable or unwilling to do so. Calling close before exhausting the stream may cause the underlying HTTP connection to be closed and prevent it from being reused for subsequent operations.charset - the character set to use when converting bytes to charactersStream<String>.public static HttpResponse.BodySubscriber<Flow.Publisher<List<ByteBuffer>>> ofPublisher()
Publisher<List<ByteBuffer>>.  The HttpResponse using this subscriber is available immediately after the response headers have been read, without requiring to wait for the entire body to be processed. The response body bytes can then be obtained by subscribing to the publisher returned by the HttpResponse body method. 
The publisher returned by the body method can be subscribed to only once. The first subscriber will receive the body response bytes if successfully subscribed, or will cause the subscription to be cancelled otherwise. If more subscriptions are attempted, the subsequent subscribers will be immediately subscribed with an empty subscription and their onError method will be invoked with an IllegalStateException.
onComplete or onError are invoked, or cancel the provided subscription if it is unable or unwilling to do so. Note that depending on the actual HTTP protocol version used for the exchange, cancelling the subscription instead of exhausting the flow may cause the underlying HTTP connection to be closed and prevent it from being reused for subsequent operations.BodySubscriber which publishes the response body through a Publisher<List<ByteBuffer>>.public static <U> HttpResponse.BodySubscriber<U> replacing(U value)
HttpResponse.body().U - the type of the response bodyvalue - the value to return from HttpResponse.body(), may be null
BodySubscriber
public static HttpResponse.BodySubscriber<Void> discarding()
public static <T> HttpResponse.BodySubscriber<T> buffering(HttpResponse.BodySubscriber<T> downstream, int bufferSize)
BodySubscriber which buffers data before delivering it to the given downstream subscriber. The subscriber guarantees to deliver bufferSize bytes of data to each invocation of the downstream's onNext method, except for the final invocation, just before onComplete is invoked. The final invocation of onNext may contain fewer than bufferSize bytes.  The returned subscriber delegates its getBody() method to the downstream subscriber.
T - the type of the response bodydownstream - the downstream subscriberbufferSize - the buffer sizeIllegalArgumentException - if bufferSize <= 0
public static <T, U> HttpResponse.BodySubscriber<U> mapping(HttpResponse.BodySubscriber<T> upstream, Function<? super T,? extends U> mapper)
BodySubscriber whose response body value is that of the result of applying the given function to the body object of the given upstream BodySubscriber.  The mapping function is executed using the client's executor, and can therefore be used to map any response body type, including blocking InputStream. However, performing any blocking operation in the mapper function runs the risk of blocking the executor's thread for an unknown amount of time (at least until the blocking operation finishes), which may end up starving the executor of available threads. Therefore, in the case where mapping to the desired type might block (e.g. by reading on the InputStream), then mapping to a Supplier of the desired type and deferring the blocking operation until Supplier::get is invoked by the caller's thread should be preferred, as shown in the following example which uses a well-known JSON parser to convert an InputStream into any annotated Java type. 
For example:
 public static <W> BodySubscriber<Supplier<W>> asJSON(Class<W> targetType) {
   BodySubscriber<InputStream> upstream = BodySubscribers.ofInputStream();
   BodySubscriber<Supplier<W>> downstream = BodySubscribers.mapping(
         upstream,
         (InputStream is) -> () -> {
             try (InputStream stream = is) {
                 ObjectMapper objectMapper = new ObjectMapper();
                 return objectMapper.readValue(stream, targetType);
             } catch (IOException e) {
                 throw new UncheckedIOException(e);
             }
         });
  return downstream;
}T - the upstream body typeU - the type of the body subscriber returnedupstream - the body subscriber to be mappedmapper - the mapping function
    © 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
    https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html