T
- the response body typeHttpResponse<T>
@FunctionalInterface public static interface HttpResponse.BodyHandler<T>
BodyHandlers
provides implementations of many common body handlers. The BodyHandler
interface allows inspection of the response code and headers, before the actual response body is received, and is responsible for creating the response BodySubscriber
. The BodySubscriber
consumes the actual response body bytes and, typically, converts them into a higher-level Java type.
A BodyHandler
is a function that takes a ResponseInfo
object; and which returns a BodySubscriber
. The BodyHandler
is invoked when the response status code and headers are available, but before the response body bytes are received.
The following example uses one of the predefined body handlers that always process the response body in the same way ( streams the response body to a file ).
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://www.foo.com/"))
.build();
client.sendAsync(request, BodyHandlers.ofFile(Paths.get("/tmp/f")))
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
HttpResponse
, when it is returned. In the second example, the function returns a different subscriber depending on the status code.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://www.foo.com/"))
.build();
BodyHandler<Path> bodyHandler = (rspInfo) -> rspInfo.statusCode() == 200
? BodySubscribers.ofFile(Paths.get("/tmp/f"))
: BodySubscribers.replacing(Paths.get("/NULL"));
client.sendAsync(request, bodyHandler)
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
Modifier and Type | Method | Description |
---|---|---|
HttpResponse.BodySubscriber |
apply |
Returns a BodySubscriber considering the given response status code and headers. |
HttpResponse.BodySubscriber<T> apply(HttpResponse.ResponseInfo responseInfo)
BodySubscriber
considering the given response status code and headers. This method is invoked before the actual response body bytes are read and its implementation must return a BodySubscriber
to consume the response body bytes. The response body can be discarded using one of discarding
or replacing
.
responseInfo
- the response info
© 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.BodyHandler.html