-
- Type Parameters:
T- the response body type
- Enclosing interface:
- 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. The classBodyHandlersprovides implementations of many common body handlers.The
BodyHandlerinterface allows inspection of the response code and headers, before the actual response body is received, and is responsible for creating the responseBodySubscriber. TheBodySubscriberconsumes the actual response body bytes and, typically, converts them into a higher-level Java type.A
BodyHandleris a function that takes aResponseInfoobject; and which returns aBodySubscriber. TheBodyHandleris 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 ).
Note, that even though the pre-defined handlers do not examine the response code, the response code and headers are always retrievable from theHttpRequest 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);- Since:
- 11
- See Also:
HttpResponse.BodyHandlers
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description HttpResponse.BodySubscriber<T>apply(HttpResponse.ResponseInfo responseInfo)Returns aBodySubscriberconsidering the given response status code and headers.
-
-
-
Method Detail
-
apply
HttpResponse.BodySubscriber<T> apply(HttpResponse.ResponseInfo responseInfo)
Returns aBodySubscriberconsidering the given response status code and headers. This method is invoked before the actual response body bytes are read and its implementation must return aBodySubscriberto consume the response body bytes.The response body can be discarded using one of
discardingorreplacing.- Parameters:
responseInfo- the response info- Returns:
- a body subscriber
-
-