- java.lang.Object
- 
- java.net.http.HttpResponse.BodySubscribers
 
- 
- Enclosing interface:
- HttpResponse<T>
 
 public static class HttpResponse.BodySubscribers extends Object Implementations ofBodySubscriberthat 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<byte[]> response = client .send(request, responseInfo -> BodySubscribers.ofByteArray()); // 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));- Since:
- 11
 
- 
- 
Method SummaryAll Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> HttpResponse.BodySubscriber<T>buffering(HttpResponse.BodySubscriber<T> downstream, int bufferSize)Returns aBodySubscriberwhich buffers data before delivering it to the given downstream subscriber.static HttpResponse.BodySubscriber<Void>discarding()Returns a response subscriber which discards the response body.static HttpResponse.BodySubscriber<Void>fromLineSubscriber(Flow.Subscriber<? super String> subscriber)Returns a body subscriber that forwards all response body to the givenFlow.Subscriber, line by line.static <S extends Flow.Subscriber<? super String>,T>
 HttpResponse.BodySubscriber<T>fromLineSubscriber(S subscriber, Function<? super S,? extends T> finisher, Charset charset, String lineSeparator)Returns a body subscriber that forwards all response body to the givenFlow.Subscriber, line by line.static HttpResponse.BodySubscriber<Void>fromSubscriber(Flow.Subscriber<? super List<ByteBuffer>> subscriber)Returns a body subscriber that forwards all response body to the givenFlow.Subscriber.static <S extends Flow.Subscriber<? super List<ByteBuffer>>,T>
 HttpResponse.BodySubscriber<T>fromSubscriber(S subscriber, Function<? super S,? extends T> finisher)Returns a body subscriber that forwards all response body to the givenFlow.Subscriber.static <T,U>
 HttpResponse.BodySubscriber<U>mapping(HttpResponse.BodySubscriber<T> upstream, Function<? super T,? extends U> mapper)Returns aBodySubscriberwhose response body value is that of the result of applying the given function to the body object of the givenupstreamBodySubscriber.static HttpResponse.BodySubscriber<byte[]>ofByteArray()Returns aBodySubscriberwhich stores the response body as a byte array.static HttpResponse.BodySubscriber<Void>ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer)Returns aBodySubscriberwhich provides the incoming body data to the provided Consumer ofOptional<byte[]>.static HttpResponse.BodySubscriber<Path>ofFile(Path file)Returns aBodySubscriberwhich stores the response body in a file opened with the given name.static HttpResponse.BodySubscriber<Path>ofFile(Path file, OpenOption... openOptions)Returns aBodySubscriberwhich stores the response body in a file opened with the given options and name.static HttpResponse.BodySubscriber<InputStream>ofInputStream()Returns aBodySubscriberwhich streams the response body as anInputStream.static HttpResponse.BodySubscriber<Stream<String>>ofLines(Charset charset)Returns aBodySubscriberwhich streams the response body as aStream, where each string in the stream corresponds to a line as defined byBufferedReader.lines().static HttpResponse.BodySubscriber<Flow.Publisher<List<ByteBuffer>>>ofPublisher()Returns a response subscriber which publishes the response body through aPublisher<List<ByteBuffer>>.static HttpResponse.BodySubscriber<String>ofString(Charset charset)Returns a body subscriber which stores the response body as aStringconverted using the givenCharset.static <U> HttpResponse.BodySubscriber<U>replacing(U value)Returns a response subscriber which discards the response body.
 
- 
- 
- 
Method Detail- 
fromSubscriberpublic static HttpResponse.BodySubscriber<Void> fromSubscriber(Flow.Subscriber<? super List<ByteBuffer>> subscriber) Returns a body subscriber that forwards all response body to the givenFlow.Subscriber. The completion stage of the returned body subscriber completes after one of the given subscribersonCompleteoronErrorhas been invoked.- API Note:
- This method can be used as an adapter between BodySubscriberandFlow.Subscriber.
- Parameters:
- subscriber- the subscriber
- Returns:
- a body subscriber
 
 - 
fromSubscriberpublic static <S extends Flow.Subscriber<? super List<ByteBuffer>>,T> HttpResponse.BodySubscriber<T> fromSubscriber(S subscriber, Function<? super S,? extends T> finisher) Returns a body subscriber that forwards all response body to the givenFlow.Subscriber. The completion stage of the returned body subscriber completes after one of the given subscribersonCompleteoronErrorhas been invoked.The given finisherfunction is applied after the given subscriber'sonCompletehas been invoked. Thefinisherfunction 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 BodySubscriberandFlow.Subscriber.
- 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 body subscriber
 
 - 
fromLineSubscriberpublic static HttpResponse.BodySubscriber<Void> fromLineSubscriber(Flow.Subscriber<? super String> subscriber) Returns a body subscriber that forwards all response body to the givenFlow.Subscriber, line by line. The completion stage of the returned body subscriber completes after one of the given subscribersonCompleteoronErrorhas been invoked. Bytes are decoded using theUTF-8charset, and lines are delimited in the manner ofBufferedReader.readLine().- API Note:
- This method can be used as an adapter between BodySubscriberandFlow.Subscriber.
- Implementation Note:
- This is equivalent to calling fromLineSubscriber(subscriber, s -> null, StandardCharsets.UTF_8, null)
- Parameters:
- subscriber- the subscriber
- Returns:
- a body subscriber
 
 - 
fromLineSubscriberpublic static <S extends Flow.Subscriber<? super String>,T> HttpResponse.BodySubscriber<T> fromLineSubscriber(S subscriber, Function<? super S,? extends T> finisher, Charset charset, String lineSeparator) Returns a body subscriber that forwards all response body to the givenFlow.Subscriber, line by line. The completion stage of the returned body subscriber completes after one of the given subscribersonCompleteoronErrorhas been invoked.The given finisherfunction is applied after the given subscriber'sonCompletehas been invoked. Thefinisherfunction 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 BodySubscriberandFlow.Subscriber.
- 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
- charset- a- Charsetto decode the bytes
- lineSeparator- an optional line separator: can be- null, in which case lines will be delimited in the manner of- BufferedReader.readLine().
- Returns:
- a body subscriber
- Throws:
- IllegalArgumentException- if the supplied- lineSeparatoris the empty string
 
 - 
ofStringpublic static HttpResponse.BodySubscriber<String> ofString(Charset charset) Returns a body subscriber which stores the response body as aStringconverted using the givenCharset.The HttpResponseusing this subscriber is available after the entire response has been read.- Parameters:
- charset- the character set to convert the String with
- Returns:
- a body subscriber
 
 - 
ofByteArraypublic static HttpResponse.BodySubscriber<byte[]> ofByteArray() Returns aBodySubscriberwhich stores the response body as a byte array.The HttpResponseusing this subscriber is available after the entire response has been read.- Returns:
- a body subscriber
 
 - 
ofFilepublic static HttpResponse.BodySubscriber<Path> ofFile(Path file, OpenOption... openOptions) Returns aBodySubscriberwhich stores the response body in a file opened with the given options and name. The file will be opened with the given options usingFileChannel.openjust before the body is read. Any exception thrown will be returned or thrown fromHttpClient::sendorHttpClient::sendAsyncas appropriate.The HttpResponseusing this subscriber is available after the entire response has been read.Security manager permission checks are performed in this factory method, when the BodySubscriberis created. Care must be taken that theBodyHandleris not shared with untrusted code.- Parameters:
- file- the file to store the body in
- openOptions- the list of options to open the file with
- Returns:
- a body subscriber
- Throws:
- IllegalArgumentException- if an invalid set of open options are specified
- SecurityException- if a security manager has been installed and it denies- write accessto the file
 
 - 
ofFilepublic static HttpResponse.BodySubscriber<Path> ofFile(Path file) Returns aBodySubscriberwhich stores the response body in a file opened with the given name.Equivalent to: ofFile(file, CREATE, WRITE)Security manager permission checks are performed in this factory method, when the BodySubscriberis created. Care must be taken that theBodyHandleris not shared with untrusted code.- Parameters:
- file- the file to store the body in
- Returns:
- a body subscriber
- Throws:
- SecurityException- if a security manager has been installed and it denies- write accessto the file
 
 - 
ofByteArrayConsumerpublic static HttpResponse.BodySubscriber<Void> ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer) Returns aBodySubscriberwhich provides the incoming body data to the provided Consumer ofOptional<byte[]>. Each call toConsumer.accept()will contain a non emptyOptional, except for the final invocation after all body data has been read, when theOptionalwill be empty.The HttpResponseusing this subscriber is available after the entire response has been read.- API Note:
- This subscriber is not flow controlled. Therefore, the supplied consumer must be able to process whatever amount of data is delivered in a timely fashion.
- Parameters:
- consumer- a Consumer of byte arrays
- Returns:
- a BodySubscriber
 
 - 
ofInputStreampublic static HttpResponse.BodySubscriber<InputStream> ofInputStream() Returns aBodySubscriberwhich streams the response body as anInputStream.The HttpResponseusing 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 theInputStream.- API Note:
- To ensure that all resources associated with the
 corresponding exchange are properly released the caller must
 ensure to either read all bytes until EOF is reached, or call
 InputStream.close()if it is unable or unwilling to do so. Callingclosebefore exhausting the stream may cause the underlying HTTP connection to be closed and prevent it from being reused for subsequent operations.
- Returns:
- a body subscriber that streams the response body as an
         InputStream.
 
 - 
ofLinespublic static HttpResponse.BodySubscriber<Stream<String>> ofLines(Charset charset) Returns aBodySubscriberwhich streams the response body as aStream, where each string in the stream corresponds to a line as defined byBufferedReader.lines().The HttpResponseusing 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 theStream.- API Note:
- To ensure that all resources associated with the
 corresponding exchange are properly released the caller must
 ensure to either read all lines until the stream is exhausted,
 or call BaseStream.close()if it is unable or unwilling to do so. Callingclosebefore exhausting the stream may cause the underlying HTTP connection to be closed and prevent it from being reused for subsequent operations.
- Parameters:
- charset- the character set to use when converting bytes to characters
- Returns:
- a body subscriber that streams the response body as a
         Stream.
- See Also:
- BufferedReader.lines()
 
 - 
ofPublisherpublic static HttpResponse.BodySubscriber<Flow.Publisher<List<ByteBuffer>>> ofPublisher() Returns a response subscriber which publishes the response body through aPublisher<List<ByteBuffer>>.The HttpResponseusing 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 theHttpResponsebodymethod.The publisher returned by the bodymethod 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 theironErrormethod will be invoked with anIllegalStateException.- API Note:
- To ensure that all resources associated with the
 corresponding exchange are properly released the caller must
 ensure that the provided publisher is subscribed once, and either
 requests all bytes
 until onCompleteoronErrorare 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.
- Returns:
- A BodySubscriberwhich publishes the response body through aPublisher<List<ByteBuffer>>.
 
 - 
replacingpublic static <U> HttpResponse.BodySubscriber<U> replacing(U value) Returns a response subscriber which discards the response body. The supplied value is the value that will be returned fromHttpResponse.body().- Type Parameters:
- U- the type of the response body
- Parameters:
- value- the value to return from HttpResponse.body(), may be- null
- Returns:
- a BodySubscriber
 
 - 
discardingpublic static HttpResponse.BodySubscriber<Void> discarding() Returns a response subscriber which discards the response body.- Returns:
- a response body subscriber
 
 - 
bufferingpublic static <T> HttpResponse.BodySubscriber<T> buffering(HttpResponse.BodySubscriber<T> downstream, int bufferSize) Returns aBodySubscriberwhich buffers data before delivering it to the given downstream subscriber. The subscriber guarantees to deliverbufferSizebytes of data to each invocation of the downstream'sonNextmethod, except for the final invocation, just beforeonCompleteis invoked. The final invocation ofonNextmay contain fewer thanbufferSizebytes.The returned subscriber delegates its getBody()method to the downstream subscriber.- Type Parameters:
- T- the type of the response body
- Parameters:
- downstream- the downstream subscriber
- bufferSize- the buffer size
- Returns:
- a buffering body subscriber
- Throws:
- IllegalArgumentException- if- bufferSize <= 0
 
 - 
mappingpublic static <T,U> HttpResponse.BodySubscriber<U> mapping(HttpResponse.BodySubscriber<T> upstream, Function<? super T,? extends U> mapper) Returns aBodySubscriberwhose response body value is that of the result of applying the given function to the body object of the givenupstreamBodySubscriber.The mapping function is executed using the client's executor, and can therefore be used to map any response body type, including blocking InputStream, as shown in the following example which uses a well-known JSON parser to convert anInputStreaminto any annotated Java type.For example: public static <W> BodySubscriber<W> asJSON(Class<W> targetType) { BodySubscriber<InputStream> upstream = BodySubscribers.ofInputStream(); BodySubscriber<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; }- Type Parameters:
- T- the upstream body type
- U- the type of the body subscriber returned
- Parameters:
- upstream- the body subscriber to be mapped
- mapper- the mapping function
- Returns:
- a mapping body subscriber
 
 
- 
 
-