Class HttpResponse.BodySubscribers
- Enclosing interface:
HttpResponse<T>
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));
- Since:
- 11
-
Method Summary
Modifier and TypeMethodDescriptionstatic <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> 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> HttpResponse.BodySubscriber<T> limiting(HttpResponse.BodySubscriber<T> downstreamSubscriber, long capacity) Returns aBodySubscriberthat limits the number of body bytes that are delivered to the givendownstreamSubscriber.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[]> 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> 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.Returns aBodySubscriberwhich streams the response body as anInputStream.static HttpResponse.BodySubscriber<Stream<String>> Returns aBodySubscriberwhich streams the response body as aStream<String>, where each string in the stream corresponds to a line as defined byBufferedReader.lines().Returns a response subscriber which publishes the response body through aPublisher<List<ByteBuffer>>.static HttpResponse.BodySubscriber<String> 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 Details
-
fromSubscriber
public 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.- Parameters:
subscriber- the subscriber- Returns:
- a body subscriber
-
fromSubscriber
public 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.- Type Parameters:
S- the type of the SubscriberT- the type of the response body- Parameters:
subscriber- the subscriberfinisher- a function to be applied after the subscriber has completed- Returns:
- a body subscriber
-
fromLineSubscriber
public 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().- Parameters:
subscriber- the subscriber- Returns:
- a body subscriber
-
fromLineSubscriber
public 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.- Type Parameters:
S- the type of the SubscriberT- the type of the response body- Parameters:
subscriber- the subscriberfinisher- a function to be applied after the subscriber has completedcharset- aCharsetto decode the byteslineSeparator- an optional line separator: can benull, in which case lines will be delimited in the manner ofBufferedReader.readLine().- Returns:
- a body subscriber
- Throws:
IllegalArgumentException- if the suppliedlineSeparatoris the empty string
-
ofString
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
-
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
-
ofFile
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.- Parameters:
file- the file to store the body inopenOptions- the list of options to open the file with- Returns:
- a body subscriber
- Throws:
IllegalArgumentException- if an invalid set of open options are specified
-
ofFile
Returns aBodySubscriberwhich stores the response body in a file opened with the given name.Equivalent to:
ofFile(file, CREATE, WRITE)- Parameters:
file- the file to store the body in- Returns:
- a body subscriber
-
ofByteArrayConsumer
public 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.- Parameters:
consumer- a Consumer of byte arrays- Returns:
- a body subscriber
-
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.- Returns:
- a streaming body subscriber
which streams the response body as an
InputStream.
-
ofLines
Returns aBodySubscriberwhich streams the response body as aStream<String>, 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.- Parameters:
charset- the character set to use when converting bytes to characters- Returns:
- a streaming body subscriber which streams
the response body as a
Stream<String>. - See Also:
-
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.- Returns:
- A publishing body subscriber
which publishes the response body
through a
Publisher<List<ByteBuffer>>.
-
replacing
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 benull- Returns:
- a body subscriber
-
discarding
Returns a response subscriber which discards the response body.- Returns:
- a response body subscriber
-
buffering
public 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 subscriberbufferSize- the buffer size- Returns:
- a buffering body subscriber
- Throws:
IllegalArgumentException- ifbufferSize <= 0
-
mapping
public 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. 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 theInputStream), then mapping to aSupplierof the desired type and deferring the blocking operation untilSupplier::getis invoked by the caller's thread should be preferred, 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<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; }- Type Parameters:
T- the upstream body typeU- the type of the body subscriber returned- Parameters:
upstream- the body subscriber to be mappedmapper- the mapping function- Returns:
- a mapping body subscriber
-
limiting
public static <T> HttpResponse.BodySubscriber<T> limiting(HttpResponse.BodySubscriber<T> downstreamSubscriber, long capacity) Returns aBodySubscriberthat limits the number of body bytes that are delivered to the givendownstreamSubscriber.If the number of body bytes received exceeds the given
capacity,onErroris called on the downstreamBodySubscriberwith anIOExceptionindicating that the capacity is exceeded, and the upstream subscription is cancelled.- Parameters:
downstreamSubscriber- the downstream subscriber to pass received data tocapacity- the maximum number of bytes that are allowed- Returns:
- a
BodySubscriberthat limits the number of body bytes that are delivered to the givendownstreamSubscriber - Throws:
IllegalArgumentException- ifcapacityis negative- Since:
- 25
-