Path: blob/master/src/java.net.http/share/classes/java/net/http/HttpResponse.java
41159 views
/*1* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net.http;2627import java.io.BufferedReader;28import java.io.IOException;29import java.io.InputStream;30import java.net.URI;31import java.nio.ByteBuffer;32import java.nio.charset.Charset;33import java.nio.channels.FileChannel;34import java.nio.charset.StandardCharsets;35import java.nio.file.OpenOption;36import java.nio.file.Path;37import java.util.List;38import java.util.Objects;39import java.util.Optional;40import java.util.concurrent.CompletableFuture;41import java.util.concurrent.CompletionStage;42import java.util.concurrent.ConcurrentMap;43import java.util.concurrent.Flow;44import java.util.concurrent.Flow.Subscriber;45import java.util.concurrent.Flow.Publisher;46import java.util.concurrent.Flow.Subscription;47import java.util.function.Consumer;48import java.util.function.Function;49import java.util.function.Supplier;50import java.util.stream.Stream;51import javax.net.ssl.SSLSession;52import jdk.internal.net.http.BufferingSubscriber;53import jdk.internal.net.http.LineSubscriberAdapter;54import jdk.internal.net.http.ResponseBodyHandlers.FileDownloadBodyHandler;55import jdk.internal.net.http.ResponseBodyHandlers.PathBodyHandler;56import jdk.internal.net.http.ResponseBodyHandlers.PushPromisesHandlerWithMap;57import jdk.internal.net.http.ResponseSubscribers;58import jdk.internal.net.http.ResponseSubscribers.PathSubscriber;59import static java.nio.file.StandardOpenOption.*;60import static jdk.internal.net.http.common.Utils.charsetFrom;6162/**63* An HTTP response.64*65* <p> An {@code HttpResponse} is not created directly, but rather returned as66* a result of sending an {@link HttpRequest}. An {@code HttpResponse} is67* made available when the response status code and headers have been received,68* and typically after the response body has also been completely received.69* Whether or not the {@code HttpResponse} is made available before the response70* body has been completely received depends on the {@link BodyHandler71* BodyHandler} provided when sending the {@code HttpRequest}.72*73* <p> This class provides methods for accessing the response status code,74* headers, the response body, and the {@code HttpRequest} corresponding75* to this response.76*77* <p> The following is an example of retrieving a response as a String:78*79* <pre>{@code HttpResponse<String> response = client80* .send(request, BodyHandlers.ofString()); }</pre>81*82* <p> The class {@link BodyHandlers BodyHandlers} provides implementations83* of many common response handlers. Alternatively, a custom {@code BodyHandler}84* implementation can be used.85*86* @param <T> the response body type87* @since 1188*/89public interface HttpResponse<T> {909192/**93* Returns the status code for this response.94*95* @return the response code96*/97public int statusCode();9899/**100* Returns the {@link HttpRequest} corresponding to this response.101*102* <p> The returned {@code HttpRequest} may not be the initiating request103* provided when {@linkplain HttpClient#send(HttpRequest, BodyHandler)104* sending}. For example, if the initiating request was redirected, then the105* request returned by this method will have the redirected URI, which will106* be different from the initiating request URI.107*108* @see #previousResponse()109*110* @return the request111*/112public HttpRequest request();113114/**115* Returns an {@code Optional} containing the previous intermediate response116* if one was received. An intermediate response is one that is received117* as a result of redirection or authentication. If no previous response118* was received then an empty {@code Optional} is returned.119*120* @return an Optional containing the HttpResponse, if any.121*/122public Optional<HttpResponse<T>> previousResponse();123124/**125* Returns the received response headers.126*127* @return the response headers128*/129public HttpHeaders headers();130131/**132* Returns the body. Depending on the type of {@code T}, the returned body133* may represent the body after it was read (such as {@code byte[]}, or134* {@code String}, or {@code Path}) or it may represent an object with135* which the body is read, such as an {@link java.io.InputStream}.136*137* <p> If this {@code HttpResponse} was returned from an invocation of138* {@link #previousResponse()} then this method returns {@code null}139*140* @return the body141*/142public T body();143144/**145* Returns an {@link Optional} containing the {@link SSLSession} in effect146* for this response. Returns an empty {@code Optional} if this is not a147* <i>HTTPS</i> response.148*149* @return an {@code Optional} containing the {@code SSLSession} associated150* with the response151*/152public Optional<SSLSession> sslSession();153154/**155* Returns the {@code URI} that the response was received from. This may be156* different from the request {@code URI} if redirection occurred.157*158* @return the URI of the response159*/160public URI uri();161162/**163* Returns the HTTP protocol version that was used for this response.164*165* @return HTTP protocol version166*/167public HttpClient.Version version();168169170/**171* Initial response information supplied to a {@link BodyHandler BodyHandler}172* when a response is initially received and before the body is processed.173*/174public interface ResponseInfo {175/**176* Provides the response status code.177* @return the response status code178*/179public int statusCode();180181/**182* Provides the response headers.183* @return the response headers184*/185public HttpHeaders headers();186187/**188* Provides the response protocol version.189* @return the response protocol version190*/191public HttpClient.Version version();192}193194/**195* A handler for response bodies. The class {@link BodyHandlers BodyHandlers}196* provides implementations of many common body handlers.197*198* <p> The {@code BodyHandler} interface allows inspection of the response199* code and headers, before the actual response body is received, and is200* responsible for creating the response {@link BodySubscriber201* BodySubscriber}. The {@code BodySubscriber} consumes the actual response202* body bytes and, typically, converts them into a higher-level Java type.203*204* <p> A {@code BodyHandler} is a function that takes a {@link ResponseInfo205* ResponseInfo} object; and which returns a {@code BodySubscriber}. The206* {@code BodyHandler} is invoked when the response status code and headers207* are available, but before the response body bytes are received.208*209* <p> The following example uses one of the {@linkplain BodyHandlers210* predefined body handlers} that always process the response body in the211* same way ( streams the response body to a file ).212*213* <pre>{@code HttpRequest request = HttpRequest.newBuilder()214* .uri(URI.create("http://www.foo.com/"))215* .build();216* client.sendAsync(request, BodyHandlers.ofFile(Paths.get("/tmp/f")))217* .thenApply(HttpResponse::body)218* .thenAccept(System.out::println); }</pre>219*220* Note, that even though the pre-defined handlers do not examine the221* response code, the response code and headers are always retrievable from222* the {@link HttpResponse}, when it is returned.223*224* <p> In the second example, the function returns a different subscriber225* depending on the status code.226* <pre>{@code HttpRequest request = HttpRequest.newBuilder()227* .uri(URI.create("http://www.foo.com/"))228* .build();229* BodyHandler<Path> bodyHandler = (rspInfo) -> rspInfo.statusCode() == 200230* ? BodySubscribers.ofFile(Paths.get("/tmp/f"))231* : BodySubscribers.replacing(Paths.get("/NULL"));232* client.sendAsync(request, bodyHandler)233* .thenApply(HttpResponse::body)234* .thenAccept(System.out::println); }</pre>235*236* @param <T> the response body type237* @see BodyHandlers238* @since 11239*/240@FunctionalInterface241public interface BodyHandler<T> {242243/**244* Returns a {@link BodySubscriber BodySubscriber} considering the245* given response status code and headers. This method is invoked before246* the actual response body bytes are read and its implementation must247* return a {@link BodySubscriber BodySubscriber} to consume the response248* body bytes.249*250* <p> The response body can be discarded using one of {@link251* BodyHandlers#discarding() discarding} or {@link252* BodyHandlers#replacing(Object) replacing}.253*254* @param responseInfo the response info255* @return a body subscriber256*/257public BodySubscriber<T> apply(ResponseInfo responseInfo);258}259260/**261* Implementations of {@link BodyHandler BodyHandler} that implement various262* useful handlers, such as handling the response body as a String, or263* streaming the response body to a file.264*265* <p> These implementations do not examine the status code, meaning the266* body is always accepted. They typically return an equivalently named267* {@code BodySubscriber}. Alternatively, a custom handler can be used to268* examine the status code and headers, and return a different body269* subscriber, of the same type, as appropriate.270*271* <p>The following are examples of using the predefined body handlers to272* convert a flow of response body data into common high-level Java objects:273*274* <pre>{@code // Receives the response body as a String275* HttpResponse<String> response = client276* .send(request, BodyHandlers.ofString());277*278* // Receives the response body as a file279* HttpResponse<Path> response = client280* .send(request, BodyHandlers.ofFile(Paths.get("example.html")));281*282* // Receives the response body as an InputStream283* HttpResponse<InputStream> response = client284* .send(request, BodyHandlers.ofInputStream());285*286* // Discards the response body287* HttpResponse<Void> response = client288* .send(request, BodyHandlers.discarding()); }</pre>289*290* @since 11291*/292public static class BodyHandlers {293294private BodyHandlers() { }295296/**297* Returns a response body handler that returns a {@link BodySubscriber298* BodySubscriber}{@code <Void>} obtained from {@link299* BodySubscribers#fromSubscriber(Subscriber)}, with the given300* {@code subscriber}.301*302* <p> The response body is not available through this, or the {@code303* HttpResponse} API, but instead all response body is forwarded to the304* given {@code subscriber}, which should make it available, if305* appropriate, through some other mechanism, e.g. an entry in a306* database, etc.307*308* @apiNote This method can be used as an adapter between {@code309* BodySubscriber} and {@code Flow.Subscriber}.310*311* <p> For example:312* <pre> {@code TextSubscriber subscriber = new TextSubscriber();313* HttpResponse<Void> response = client.sendAsync(request,314* BodyHandlers.fromSubscriber(subscriber)).join();315* System.out.println(response.statusCode()); }</pre>316*317* @param subscriber the subscriber318* @return a response body handler319*/320public static BodyHandler<Void>321fromSubscriber(Subscriber<? super List<ByteBuffer>> subscriber) {322Objects.requireNonNull(subscriber);323return (responseInfo) -> BodySubscribers.fromSubscriber(subscriber,324s -> null);325}326327/**328* Returns a response body handler that returns a {@link BodySubscriber329* BodySubscriber}{@code <T>} obtained from {@link330* BodySubscribers#fromSubscriber(Subscriber, Function)}, with the331* given {@code subscriber} and {@code finisher} function.332*333* <p> The given {@code finisher} function is applied after the given334* subscriber's {@code onComplete} has been invoked. The {@code finisher}335* function is invoked with the given subscriber, and returns a value336* that is set as the response's body.337*338* @apiNote This method can be used as an adapter between {@code339* BodySubscriber} and {@code Flow.Subscriber}.340*341* <p> For example:342* <pre> {@code TextSubscriber subscriber = ...; // accumulates bytes and transforms them into a String343* HttpResponse<String> response = client.sendAsync(request,344* BodyHandlers.fromSubscriber(subscriber, TextSubscriber::getTextResult)).join();345* String text = response.body(); }</pre>346*347* @param <S> the type of the Subscriber348* @param <T> the type of the response body349* @param subscriber the subscriber350* @param finisher a function to be applied after the subscriber has completed351* @return a response body handler352*/353public static <S extends Subscriber<? super List<ByteBuffer>>,T> BodyHandler<T>354fromSubscriber(S subscriber, Function<? super S,? extends T> finisher) {355Objects.requireNonNull(subscriber);356Objects.requireNonNull(finisher);357return (responseInfo) -> BodySubscribers.fromSubscriber(subscriber,358finisher);359}360361/**362* Returns a response body handler that returns a {@link BodySubscriber363* BodySubscriber}{@code <Void>} obtained from {@link364* BodySubscribers#fromLineSubscriber(Subscriber, Function, Charset, String)365* BodySubscribers.fromLineSubscriber(subscriber, s -> null, charset, null)},366* with the given {@code subscriber}.367* The {@link Charset charset} used to decode the response body bytes is368* obtained from the HTTP response headers as specified by {@link #ofString()},369* and lines are delimited in the manner of {@link BufferedReader#readLine()}.370*371* <p> The response body is not available through this, or the {@code372* HttpResponse} API, but instead all response body is forwarded to the373* given {@code subscriber}, which should make it available, if374* appropriate, through some other mechanism, e.g. an entry in a375* database, etc.376*377* @apiNote This method can be used as an adapter between a {@code378* BodySubscriber} and a text based {@code Flow.Subscriber} that parses379* text line by line.380*381* <p> For example:382* <pre> {@code // A PrintSubscriber that implements Flow.Subscriber<String>383* // and print lines received by onNext() on System.out384* PrintSubscriber subscriber = new PrintSubscriber(System.out);385* client.sendAsync(request, BodyHandlers.fromLineSubscriber(subscriber))386* .thenApply(HttpResponse::statusCode)387* .thenAccept((status) -> {388* if (status != 200) {389* System.err.printf("ERROR: %d status received%n", status);390* }391* }); }</pre>392*393* @param subscriber the subscriber394* @return a response body handler395*/396public static BodyHandler<Void>397fromLineSubscriber(Subscriber<? super String> subscriber) {398Objects.requireNonNull(subscriber);399return (responseInfo) ->400BodySubscribers.fromLineSubscriber(subscriber,401s -> null,402charsetFrom(responseInfo.headers()),403null);404}405406/**407* Returns a response body handler that returns a {@link BodySubscriber408* BodySubscriber}{@code <T>} obtained from {@link409* BodySubscribers#fromLineSubscriber(Subscriber, Function, Charset, String)410* BodySubscribers.fromLineSubscriber(subscriber, finisher, charset, lineSeparator)},411* with the given {@code subscriber}, {@code finisher} function, and line separator.412* The {@link Charset charset} used to decode the response body bytes is413* obtained from the HTTP response headers as specified by {@link #ofString()}.414*415* <p> The given {@code finisher} function is applied after the given416* subscriber's {@code onComplete} has been invoked. The {@code finisher}417* function is invoked with the given subscriber, and returns a value418* that is set as the response's body.419*420* @apiNote This method can be used as an adapter between a {@code421* BodySubscriber} and a text based {@code Flow.Subscriber} that parses422* text line by line.423*424* <p> For example:425* <pre> {@code // A LineParserSubscriber that implements Flow.Subscriber<String>426* // and accumulates lines that match a particular pattern427* Pattern pattern = ...;428* LineParserSubscriber subscriber = new LineParserSubscriber(pattern);429* HttpResponse<List<String>> response = client.send(request,430* BodyHandlers.fromLineSubscriber(subscriber, s -> s.getMatchingLines(), "\n"));431* if (response.statusCode() != 200) {432* System.err.printf("ERROR: %d status received%n", response.statusCode());433* } }</pre>434*435*436* @param <S> the type of the Subscriber437* @param <T> the type of the response body438* @param subscriber the subscriber439* @param finisher a function to be applied after the subscriber has completed440* @param lineSeparator an optional line separator: can be {@code null},441* in which case lines will be delimited in the manner of442* {@link BufferedReader#readLine()}.443* @return a response body handler444* @throws IllegalArgumentException if the supplied {@code lineSeparator}445* is the empty string446*/447public static <S extends Subscriber<? super String>,T> BodyHandler<T>448fromLineSubscriber(S subscriber,449Function<? super S,? extends T> finisher,450String lineSeparator) {451Objects.requireNonNull(subscriber);452Objects.requireNonNull(finisher);453// implicit null check454if (lineSeparator != null && lineSeparator.isEmpty())455throw new IllegalArgumentException("empty line separator");456return (responseInfo) ->457BodySubscribers.fromLineSubscriber(subscriber,458finisher,459charsetFrom(responseInfo.headers()),460lineSeparator);461}462463/**464* Returns a response body handler that discards the response body.465*466* @return a response body handler467*/468public static BodyHandler<Void> discarding() {469return (responseInfo) -> BodySubscribers.discarding();470}471472/**473* Returns a response body handler that returns the given replacement474* value, after discarding the response body.475*476* @param <U> the response body type477* @param value the value of U to return as the body, may be {@code null}478* @return a response body handler479*/480public static <U> BodyHandler<U> replacing(U value) {481return (responseInfo) -> BodySubscribers.replacing(value);482}483484/**485* Returns a {@code BodyHandler<String>} that returns a486* {@link BodySubscriber BodySubscriber}{@code <String>} obtained from487* {@link BodySubscribers#ofString(Charset) BodySubscribers.ofString(Charset)}.488* The body is decoded using the given character set.489*490* @param charset the character set to convert the body with491* @return a response body handler492*/493public static BodyHandler<String> ofString(Charset charset) {494Objects.requireNonNull(charset);495return (responseInfo) -> BodySubscribers.ofString(charset);496}497498/**499* Returns a {@code BodyHandler<Path>} that returns a500* {@link BodySubscriber BodySubscriber}{@code <Path>} obtained from501* {@link BodySubscribers#ofFile(Path, OpenOption...)502* BodySubscribers.ofFile(Path,OpenOption...)}.503*504* <p> When the {@code HttpResponse} object is returned, the body has505* been completely written to the file, and {@link #body()} returns a506* reference to its {@link Path}.507*508* <p> In the case of the default file system provider, security manager509* permission checks are performed in this factory method, when the510* {@code BodyHandler} is created. Otherwise,511* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}512* may be performed asynchronously against the caller's context513* at file access time.514* Care must be taken that the {@code BodyHandler} is not shared with515* untrusted code.516*517* @param file the file to store the body in518* @param openOptions any options to use when opening/creating the file519* @return a response body handler520* @throws IllegalArgumentException if an invalid set of open options521* are specified522* @throws SecurityException in the case of the default file system523* provider, and a security manager is installed,524* {@link SecurityManager#checkWrite(String) checkWrite}525* is invoked to check write access to the given file526*/527public static BodyHandler<Path> ofFile(Path file, OpenOption... openOptions) {528Objects.requireNonNull(file);529List<OpenOption> opts = List.of(openOptions);530if (opts.contains(DELETE_ON_CLOSE) || opts.contains(READ)) {531// these options make no sense, since the FileChannel is not exposed532throw new IllegalArgumentException("invalid openOptions: " + opts);533}534return PathBodyHandler.create(file, opts);535}536537/**538* Returns a {@code BodyHandler<Path>} that returns a539* {@link BodySubscriber BodySubscriber}{@code <Path>}.540*541* <p> Equivalent to: {@code ofFile(file, CREATE, WRITE)}542*543* <p> In the case of the default file system provider, security manager544* permission checks are performed in this factory method, when the545* {@code BodyHandler} is created. Otherwise,546* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}547* may be performed asynchronously against the caller's context548* at file access time.549* Care must be taken that the {@code BodyHandler} is not shared with550* untrusted code.551*552* @param file the file to store the body in553* @return a response body handler554* @throws SecurityException in the case of the default file system555* provider, and a security manager is installed,556* {@link SecurityManager#checkWrite(String) checkWrite}557* is invoked to check write access to the given file558*/559public static BodyHandler<Path> ofFile(Path file) {560return BodyHandlers.ofFile(file, CREATE, WRITE);561}562563/**564* Returns a {@code BodyHandler<Path>} that returns a565* {@link BodySubscriber BodySubscriber}<{@link Path}>566* where the download directory is specified, but the filename is567* obtained from the {@code Content-Disposition} response header. The568* {@code Content-Disposition} header must specify the <i>attachment</i>569* type and must also contain a <i>filename</i> parameter. If the570* filename specifies multiple path components only the final component571* is used as the filename (with the given directory name).572*573* <p> When the {@code HttpResponse} object is returned, the body has574* been completely written to the file and {@link #body()} returns a575* {@code Path} object for the file. The returned {@code Path} is the576* combination of the supplied directory name and the file name supplied577* by the server. If the destination directory does not exist or cannot578* be written to, then the response will fail with an {@link IOException}.579*580* <p> Security manager permission checks are performed in this factory581* method, when the {@code BodyHandler} is created. Care must be taken582* that the {@code BodyHandler} is not shared with untrusted code.583*584* @param directory the directory to store the file in585* @param openOptions open options used when opening the file586* @return a response body handler587* @throws IllegalArgumentException if the given path does not exist,588* is not of the default file system, is not a directory,589* is not writable, or if an invalid set of open options590* are specified591* @throws SecurityException in the case of the default file system592* provider and a security manager has been installed,593* and it denies594* {@linkplain SecurityManager#checkRead(String) read access}595* to the directory, or it denies596* {@linkplain SecurityManager#checkWrite(String) write access}597* to the directory, or it denies598* {@linkplain SecurityManager#checkWrite(String) write access}599* to the files within the directory.600*/601public static BodyHandler<Path> ofFileDownload(Path directory,602OpenOption... openOptions) {603Objects.requireNonNull(directory);604List<OpenOption> opts = List.of(openOptions);605if (opts.contains(DELETE_ON_CLOSE)) {606throw new IllegalArgumentException("invalid option: " + DELETE_ON_CLOSE);607}608return FileDownloadBodyHandler.create(directory, opts);609}610611/**612* Returns a {@code BodyHandler<InputStream>} that returns a613* {@link BodySubscriber BodySubscriber}{@code <InputStream>} obtained from614* {@link BodySubscribers#ofInputStream() BodySubscribers.ofInputStream}.615*616* <p> When the {@code HttpResponse} object is returned, the response617* headers will have been completely read, but the body may not have618* been fully received yet. The {@link #body()} method returns an619* {@link InputStream} from which the body can be read as it is received.620*621* @apiNote See {@link BodySubscribers#ofInputStream()} for more622* information.623*624* @return a response body handler625*/626public static BodyHandler<InputStream> ofInputStream() {627return (responseInfo) -> BodySubscribers.ofInputStream();628}629630/**631* Returns a {@code BodyHandler<Stream<String>>} that returns a632* {@link BodySubscriber BodySubscriber}{@code <Stream<String>>} obtained633* from {@link BodySubscribers#ofLines(Charset) BodySubscribers.ofLines(charset)}.634* The {@link Charset charset} used to decode the response body bytes is635* obtained from the HTTP response headers as specified by {@link #ofString()},636* and lines are delimited in the manner of {@link BufferedReader#readLine()}.637*638* <p> When the {@code HttpResponse} object is returned, the body may639* not have been completely received.640*641* @return a response body handler642*/643public static BodyHandler<Stream<String>> ofLines() {644return (responseInfo) ->645BodySubscribers.ofLines(charsetFrom(responseInfo.headers()));646}647648/**649* Returns a {@code BodyHandler<Void>} that returns a650* {@link BodySubscriber BodySubscriber}{@code <Void>} obtained from651* {@link BodySubscribers#ofByteArrayConsumer(Consumer)652* BodySubscribers.ofByteArrayConsumer(Consumer)}.653*654* <p> When the {@code HttpResponse} object is returned, the body has655* been completely written to the consumer.656*657* @apiNote658* The subscriber returned by this handler is not flow controlled.659* Therefore, the supplied consumer must be able to process whatever660* amount of data is delivered in a timely fashion.661*662* @param consumer a Consumer to accept the response body663* @return a response body handler664*/665public static BodyHandler<Void>666ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer) {667Objects.requireNonNull(consumer);668return (responseInfo) -> BodySubscribers.ofByteArrayConsumer(consumer);669}670671/**672* Returns a {@code BodyHandler<byte[]>} that returns a673* {@link BodySubscriber BodySubscriber}{@code <byte[]>} obtained674* from {@link BodySubscribers#ofByteArray() BodySubscribers.ofByteArray()}.675*676* <p> When the {@code HttpResponse} object is returned, the body has677* been completely written to the byte array.678*679* @return a response body handler680*/681public static BodyHandler<byte[]> ofByteArray() {682return (responseInfo) -> BodySubscribers.ofByteArray();683}684685/**686* Returns a {@code BodyHandler<String>} that returns a687* {@link BodySubscriber BodySubscriber}{@code <String>} obtained from688* {@link BodySubscribers#ofString(Charset) BodySubscribers.ofString(Charset)}.689* The body is decoded using the character set specified in690* the {@code Content-Type} response header. If there is no such691* header, or the character set is not supported, then692* {@link StandardCharsets#UTF_8 UTF_8} is used.693*694* <p> When the {@code HttpResponse} object is returned, the body has695* been completely written to the string.696*697* @return a response body handler698*/699public static BodyHandler<String> ofString() {700return (responseInfo) -> BodySubscribers.ofString(charsetFrom(responseInfo.headers()));701}702703/**704* Returns a {@code BodyHandler<Publisher<List<ByteBuffer>>>} that creates a705* {@link BodySubscriber BodySubscriber}{@code <Publisher<List<ByteBuffer>>>}706* obtained from {@link BodySubscribers#ofPublisher()707* BodySubscribers.ofPublisher()}.708*709* <p> When the {@code HttpResponse} object is returned, the response710* headers will have been completely read, but the body may not have711* been fully received yet. The {@link #body()} method returns a712* {@link Publisher Publisher}{@code <List<ByteBuffer>>} from which the body713* response bytes can be obtained as they are received. The publisher714* can and must be subscribed to only once.715*716* @apiNote See {@link BodySubscribers#ofPublisher()} for more717* information.718*719* @return a response body handler720*/721public static BodyHandler<Publisher<List<ByteBuffer>>> ofPublisher() {722return (responseInfo) -> BodySubscribers.ofPublisher();723}724725/**726* Returns a {@code BodyHandler} which, when invoked, returns a {@linkplain727* BodySubscribers#buffering(BodySubscriber,int) buffering BodySubscriber}728* that buffers data before delivering it to the downstream subscriber.729* These {@code BodySubscriber} instances are created by calling730* {@link BodySubscribers#buffering(BodySubscriber,int)731* BodySubscribers.buffering} with a subscriber obtained from the given732* downstream handler and the {@code bufferSize} parameter.733*734* @param <T> the response body type735* @param downstreamHandler the downstream handler736* @param bufferSize the buffer size parameter passed to {@link737* BodySubscribers#buffering(BodySubscriber,int) BodySubscribers.buffering}738* @return a body handler739* @throws IllegalArgumentException if {@code bufferSize <= 0}740*/741public static <T> BodyHandler<T> buffering(BodyHandler<T> downstreamHandler,742int bufferSize) {743Objects.requireNonNull(downstreamHandler);744if (bufferSize <= 0)745throw new IllegalArgumentException("must be greater than 0");746return (responseInfo) -> BodySubscribers747.buffering(downstreamHandler.apply(responseInfo),748bufferSize);749}750}751752/**753* A handler for push promises.754*755* <p> A <i>push promise</i> is a synthetic request sent by an HTTP/2 server756* when retrieving an initiating client-sent request. The server has757* determined, possibly through inspection of the initiating request, that758* the client will likely need the promised resource, and hence pushes a759* synthetic push request, in the form of a push promise, to the client. The760* client can choose to accept or reject the push promise request.761*762* <p> A push promise request may be received up to the point where the763* response body of the initiating client-sent request has been fully764* received. The delivery of a push promise response, however, is not765* coordinated with the delivery of the response to the initiating766* client-sent request.767*768* @param <T> the push promise response body type769* @since 11770*/771public interface PushPromiseHandler<T> {772773/**774* Notification of an incoming push promise.775*776* <p> This method is invoked once for each push promise received, up777* to the point where the response body of the initiating client-sent778* request has been fully received.779*780* <p> A push promise is accepted by invoking the given {@code acceptor}781* function. The {@code acceptor} function must be passed a non-null782* {@code BodyHandler}, that is to be used to handle the promise's783* response body. The acceptor function will return a {@code784* CompletableFuture} that completes with the promise's response.785*786* <p> If the {@code acceptor} function is not successfully invoked,787* then the push promise is rejected. The {@code acceptor} function will788* throw an {@code IllegalStateException} if invoked more than once.789*790* @param initiatingRequest the initiating client-send request791* @param pushPromiseRequest the synthetic push request792* @param acceptor the acceptor function that must be successfully793* invoked to accept the push promise794*/795public void applyPushPromise(796HttpRequest initiatingRequest,797HttpRequest pushPromiseRequest,798Function<HttpResponse.BodyHandler<T>,CompletableFuture<HttpResponse<T>>> acceptor799);800801802/**803* Returns a push promise handler that accumulates push promises, and804* their responses, into the given map.805*806* <p> Entries are added to the given map for each push promise accepted.807* The entry's key is the push request, and the entry's value is a808* {@code CompletableFuture} that completes with the response809* corresponding to the key's push request. A push request is rejected /810* cancelled if there is already an entry in the map whose key is811* {@linkplain HttpRequest#equals equal} to it. A push request is812* rejected / cancelled if it does not have the same origin as its813* initiating request.814*815* <p> Entries are added to the given map as soon as practically816* possible when a push promise is received and accepted. That way code,817* using such a map like a cache, can determine if a push promise has818* been issued by the server and avoid making, possibly, unnecessary819* requests.820*821* <p> The delivery of a push promise response is not coordinated with822* the delivery of the response to the initiating client-sent request.823* However, when the response body for the initiating client-sent824* request has been fully received, the map is guaranteed to be fully825* populated, that is, no more entries will be added. The individual826* {@code CompletableFutures} contained in the map may or may not827* already be completed at this point.828*829* @param <T> the push promise response body type830* @param pushPromiseHandler t he body handler to use for push promises831* @param pushPromisesMap a map to accumulate push promises into832* @return a push promise handler833*/834public static <T> PushPromiseHandler<T>835of(Function<HttpRequest,BodyHandler<T>> pushPromiseHandler,836ConcurrentMap<HttpRequest,CompletableFuture<HttpResponse<T>>> pushPromisesMap) {837return new PushPromisesHandlerWithMap<>(pushPromiseHandler, pushPromisesMap);838}839}840841/**842* A {@code BodySubscriber} consumes response body bytes and converts them843* into a higher-level Java type. The class {@link BodySubscribers844* BodySubscribers} provides implementations of many common body subscribers.845*846* <p> The object acts as a {@link Flow.Subscriber}<{@link List}<{@link847* ByteBuffer}>> to the HTTP Client implementation, which publishes848* lists of ByteBuffers containing the response body. The Flow of data, as849* well as the order of ByteBuffers in the Flow lists, is a strictly ordered850* representation of the response body. Both the Lists and the ByteBuffers,851* once passed to the subscriber, are no longer used by the HTTP Client. The852* subscriber converts the incoming buffers of data to some higher-level853* Java type {@code T}.854*855* <p> The {@link #getBody()} method returns a856* {@link CompletionStage}{@code <T>} that provides the response body857* object. The {@code CompletionStage} must be obtainable at any time. When858* it completes depends on the nature of type {@code T}. In many cases,859* when {@code T} represents the entire body after being consumed then860* the {@code CompletionStage} completes after the body has been consumed.861* If {@code T} is a streaming type, such as {@link java.io.InputStream862* InputStream}, then it completes before the body has been read, because863* the calling code uses the {@code InputStream} to consume the data.864*865* @apiNote To ensure that all resources associated with the corresponding866* HTTP exchange are properly released, an implementation of {@code867* BodySubscriber} should ensure to {@linkplain Flow.Subscription#request868* request} more data until one of {@link #onComplete() onComplete} or869* {@link #onError(Throwable) onError} are signalled, or {@link870* Flow.Subscription#request cancel} its {@linkplain871* #onSubscribe(Flow.Subscription) subscription} if unable or unwilling to872* do so. Calling {@code cancel} before exhausting the response body data873* may cause the underlying HTTP connection to be closed and prevent it874* from being reused for subsequent operations.875*876* @implNote The flow of data containing the response body is immutable.877* Specifically, it is a flow of unmodifiable lists of read-only ByteBuffers.878*879* @param <T> the response body type880* @see BodySubscribers881* @since 11882*/883public interface BodySubscriber<T>884extends Flow.Subscriber<List<ByteBuffer>> {885886/**887* Returns a {@code CompletionStage} which when completed will return888* the response body object. This method can be called at any time889* relative to the other {@link Flow.Subscriber} methods and is invoked890* using the client's {@link HttpClient#executor() executor}.891*892* @return a CompletionStage for the response body893*/894public CompletionStage<T> getBody();895}896897/**898* Implementations of {@link BodySubscriber BodySubscriber} that implement899* various useful subscribers, such as converting the response body bytes900* into a String, or streaming the bytes to a file.901*902* <p>The following are examples of using the predefined body subscribers903* to convert a flow of response body data into common high-level Java904* objects:905*906* <pre>{@code // Streams the response body to a File907* HttpResponse<Path> response = client908* .send(request, responseInfo -> BodySubscribers.ofFile(Paths.get("example.html"));909*910* // Accumulates the response body and returns it as a byte[]911* HttpResponse<byte[]> response = client912* .send(request, responseInfo -> BodySubscribers.ofByteArray());913*914* // Discards the response body915* HttpResponse<Void> response = client916* .send(request, responseInfo -> BodySubscribers.discarding());917*918* // Accumulates the response body as a String then maps it to its bytes919* HttpResponse<byte[]> response = client920* .send(request, responseInfo ->921* BodySubscribers.mapping(BodySubscribers.ofString(UTF_8), String::getBytes));922* }</pre>923*924* @since 11925*/926public static class BodySubscribers {927928private BodySubscribers() { }929930/**931* Returns a body subscriber that forwards all response body to the932* given {@code Flow.Subscriber}. The {@linkplain BodySubscriber#getBody()933* completion stage} of the returned body subscriber completes after one934* of the given subscribers {@code onComplete} or {@code onError} has935* been invoked.936*937* @apiNote This method can be used as an adapter between {@code938* BodySubscriber} and {@code Flow.Subscriber}.939*940* @param subscriber the subscriber941* @return a body subscriber942*/943public static BodySubscriber<Void>944fromSubscriber(Subscriber<? super List<ByteBuffer>> subscriber) {945return new ResponseSubscribers.SubscriberAdapter<>(subscriber, s -> null);946}947948/**949* Returns a body subscriber that forwards all response body to the950* given {@code Flow.Subscriber}. The {@linkplain BodySubscriber#getBody()951* completion stage} of the returned body subscriber completes after one952* of the given subscribers {@code onComplete} or {@code onError} has953* been invoked.954*955* <p> The given {@code finisher} function is applied after the given956* subscriber's {@code onComplete} has been invoked. The {@code finisher}957* function is invoked with the given subscriber, and returns a value958* that is set as the response's body.959*960* @apiNote This method can be used as an adapter between {@code961* BodySubscriber} and {@code Flow.Subscriber}.962*963* @param <S> the type of the Subscriber964* @param <T> the type of the response body965* @param subscriber the subscriber966* @param finisher a function to be applied after the subscriber has967* completed968* @return a body subscriber969*/970public static <S extends Subscriber<? super List<ByteBuffer>>,T> BodySubscriber<T>971fromSubscriber(S subscriber,972Function<? super S,? extends T> finisher) {973return new ResponseSubscribers.SubscriberAdapter<>(subscriber, finisher);974}975976/**977* Returns a body subscriber that forwards all response body to the978* given {@code Flow.Subscriber}, line by line.979* The {@linkplain BodySubscriber#getBody() completion980* stage} of the returned body subscriber completes after one of the981* given subscribers {@code onComplete} or {@code onError} has been982* invoked.983* Bytes are decoded using the {@link StandardCharsets#UTF_8984* UTF-8} charset, and lines are delimited in the manner of985* {@link BufferedReader#readLine()}.986*987* @apiNote This method can be used as an adapter between {@code988* BodySubscriber} and {@code Flow.Subscriber}.989*990* @implNote This is equivalent to calling <pre>{@code991* fromLineSubscriber(subscriber, s -> null, StandardCharsets.UTF_8, null)992* }</pre>993*994* @param subscriber the subscriber995* @return a body subscriber996*/997public static BodySubscriber<Void>998fromLineSubscriber(Subscriber<? super String> subscriber) {999return fromLineSubscriber(subscriber, s -> null,1000StandardCharsets.UTF_8, null);1001}10021003/**1004* Returns a body subscriber that forwards all response body to the1005* given {@code Flow.Subscriber}, line by line. The {@linkplain1006* BodySubscriber#getBody() completion stage} of the returned body1007* subscriber completes after one of the given subscribers1008* {@code onComplete} or {@code onError} has been invoked.1009*1010* <p> The given {@code finisher} function is applied after the given1011* subscriber's {@code onComplete} has been invoked. The {@code finisher}1012* function is invoked with the given subscriber, and returns a value1013* that is set as the response's body.1014*1015* @apiNote This method can be used as an adapter between {@code1016* BodySubscriber} and {@code Flow.Subscriber}.1017*1018* @param <S> the type of the Subscriber1019* @param <T> the type of the response body1020* @param subscriber the subscriber1021* @param finisher a function to be applied after the subscriber has1022* completed1023* @param charset a {@link Charset} to decode the bytes1024* @param lineSeparator an optional line separator: can be {@code null},1025* in which case lines will be delimited in the manner of1026* {@link BufferedReader#readLine()}.1027* @return a body subscriber1028* @throws IllegalArgumentException if the supplied {@code lineSeparator}1029* is the empty string1030*/1031public static <S extends Subscriber<? super String>,T> BodySubscriber<T>1032fromLineSubscriber(S subscriber,1033Function<? super S,? extends T> finisher,1034Charset charset,1035String lineSeparator) {1036return LineSubscriberAdapter.create(subscriber,1037finisher, charset, lineSeparator);1038}10391040/**1041* Returns a body subscriber which stores the response body as a {@code1042* String} converted using the given {@code Charset}.1043*1044* <p> The {@link HttpResponse} using this subscriber is available after1045* the entire response has been read.1046*1047* @param charset the character set to convert the String with1048* @return a body subscriber1049*/1050public static BodySubscriber<String> ofString(Charset charset) {1051Objects.requireNonNull(charset);1052return new ResponseSubscribers.ByteArraySubscriber<>(1053bytes -> new String(bytes, charset)1054);1055}10561057/**1058* Returns a {@code BodySubscriber} which stores the response body as a1059* byte array.1060*1061* <p> The {@link HttpResponse} using this subscriber is available after1062* the entire response has been read.1063*1064* @return a body subscriber1065*/1066public static BodySubscriber<byte[]> ofByteArray() {1067return new ResponseSubscribers.ByteArraySubscriber<>(1068Function.identity() // no conversion1069);1070}10711072/**1073* Returns a {@code BodySubscriber} which stores the response body in a1074* file opened with the given options and name. The file will be opened1075* with the given options using {@link FileChannel#open(Path,OpenOption...)1076* FileChannel.open} just before the body is read. Any exception thrown1077* will be returned or thrown from {@link HttpClient#send(HttpRequest,1078* BodyHandler) HttpClient::send} or {@link HttpClient#sendAsync(HttpRequest,1079* BodyHandler) HttpClient::sendAsync} as appropriate.1080*1081* <p> The {@link HttpResponse} using this subscriber is available after1082* the entire response has been read.1083*1084* <p> In the case of the default file system provider, security manager1085* permission checks are performed in this factory method, when the1086* {@code BodySubscriber} is created. Otherwise,1087* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}1088* may be performed asynchronously against the caller's context1089* at file access time.1090* Care must be taken that the {@code BodySubscriber} is not shared with1091* untrusted code.1092*1093* @param file the file to store the body in1094* @param openOptions the list of options to open the file with1095* @return a body subscriber1096* @throws IllegalArgumentException if an invalid set of open options1097* are specified1098* @throws SecurityException in the case of the default file system1099* provider, and a security manager is installed,1100* {@link SecurityManager#checkWrite(String) checkWrite}1101* is invoked to check write access to the given file1102*/1103public static BodySubscriber<Path> ofFile(Path file, OpenOption... openOptions) {1104Objects.requireNonNull(file);1105List<OpenOption> opts = List.of(openOptions);1106if (opts.contains(DELETE_ON_CLOSE) || opts.contains(READ)) {1107// these options make no sense, since the FileChannel is not exposed1108throw new IllegalArgumentException("invalid openOptions: " + opts);1109}1110return PathSubscriber.create(file, opts);1111}11121113/**1114* Returns a {@code BodySubscriber} which stores the response body in a1115* file opened with the given name.1116*1117* <p> Equivalent to: {@code ofFile(file, CREATE, WRITE)}1118*1119* <p> In the case of the default file system provider, security manager1120* permission checks are performed in this factory method, when the1121* {@code BodySubscriber} is created. Otherwise,1122* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}1123* may be performed asynchronously against the caller's context1124* at file access time.1125* Care must be taken that the {@code BodySubscriber} is not shared with1126* untrusted code.1127*1128* @param file the file to store the body in1129* @return a body subscriber1130* @throws SecurityException in the case of the default file system1131* provider, and a security manager is installed,1132* {@link SecurityManager#checkWrite(String) checkWrite}1133* is invoked to check write access to the given file1134*/1135public static BodySubscriber<Path> ofFile(Path file) {1136return ofFile(file, CREATE, WRITE);1137}11381139/**1140* Returns a {@code BodySubscriber} which provides the incoming body1141* data to the provided Consumer of {@code Optional<byte[]>}. Each1142* call to {@link Consumer#accept(java.lang.Object) Consumer.accept()}1143* will contain a non empty {@code Optional}, except for the final1144* invocation after all body data has been read, when the {@code1145* Optional} will be empty.1146*1147* <p> The {@link HttpResponse} using this subscriber is available after1148* the entire response has been read.1149*1150* @apiNote1151* This subscriber is not flow controlled.1152* Therefore, the supplied consumer must be able to process whatever1153* amount of data is delivered in a timely fashion.1154*1155* @param consumer a Consumer of byte arrays1156* @return a BodySubscriber1157*/1158public static BodySubscriber<Void>1159ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer) {1160return new ResponseSubscribers.ConsumerSubscriber(consumer);1161}11621163/**1164* Returns a {@code BodySubscriber} which streams the response body as1165* an {@link InputStream}.1166*1167* <p> The {@link HttpResponse} using this subscriber is available1168* immediately after the response headers have been read, without1169* requiring to wait for the entire body to be processed. The response1170* body can then be read directly from the {@link InputStream}.1171*1172* @apiNote To ensure that all resources associated with the1173* corresponding exchange are properly released the caller must1174* ensure to either read all bytes until EOF is reached, or call1175* {@link InputStream#close} if it is unable or unwilling to do so.1176* Calling {@code close} before exhausting the stream may cause1177* the underlying HTTP connection to be closed and prevent it1178* from being reused for subsequent operations.1179*1180* @return a body subscriber that streams the response body as an1181* {@link InputStream}.1182*/1183public static BodySubscriber<InputStream> ofInputStream() {1184return new ResponseSubscribers.HttpResponseInputStream();1185}11861187/**1188* Returns a {@code BodySubscriber} which streams the response body as1189* a {@link Stream Stream}{@code <String>}, where each string in the stream1190* corresponds to a line as defined by {@link BufferedReader#lines()}.1191*1192* <p> The {@link HttpResponse} using this subscriber is available1193* immediately after the response headers have been read, without1194* requiring to wait for the entire body to be processed. The response1195* body can then be read directly from the {@link Stream}.1196*1197* @apiNote To ensure that all resources associated with the1198* corresponding exchange are properly released the caller must1199* ensure to either read all lines until the stream is exhausted,1200* or call {@link Stream#close} if it is unable or unwilling to do so.1201* Calling {@code close} before exhausting the stream may cause1202* the underlying HTTP connection to be closed and prevent it1203* from being reused for subsequent operations.1204*1205* @param charset the character set to use when converting bytes to characters1206* @return a body subscriber that streams the response body as a1207* {@link Stream Stream}{@code <String>}.1208*1209* @see BufferedReader#lines()1210*/1211public static BodySubscriber<Stream<String>> ofLines(Charset charset) {1212return ResponseSubscribers.createLineStream(charset);1213}12141215/**1216* Returns a response subscriber which publishes the response body1217* through a {@code Publisher<List<ByteBuffer>>}.1218*1219* <p> The {@link HttpResponse} using this subscriber is available1220* immediately after the response headers have been read, without1221* requiring to wait for the entire body to be processed. The response1222* body bytes can then be obtained by subscribing to the publisher1223* returned by the {@code HttpResponse} {@link HttpResponse#body() body}1224* method.1225*1226* <p>The publisher returned by the {@link HttpResponse#body() body}1227* method can be subscribed to only once. The first subscriber will1228* receive the body response bytes if successfully subscribed, or will1229* cause the subscription to be cancelled otherwise.1230* If more subscriptions are attempted, the subsequent subscribers will1231* be immediately subscribed with an empty subscription and their1232* {@link Subscriber#onError(Throwable) onError} method1233* will be invoked with an {@code IllegalStateException}.1234*1235* @apiNote To ensure that all resources associated with the1236* corresponding exchange are properly released the caller must1237* ensure that the provided publisher is subscribed once, and either1238* {@linkplain Subscription#request(long) requests} all bytes1239* until {@link Subscriber#onComplete() onComplete} or1240* {@link Subscriber#onError(Throwable) onError} are invoked, or1241* cancel the provided {@linkplain Subscriber#onSubscribe(Subscription)1242* subscription} if it is unable or unwilling to do so.1243* Note that depending on the actual HTTP protocol {@linkplain1244* HttpClient.Version version} used for the exchange, cancelling the1245* subscription instead of exhausting the flow may cause the underlying1246* HTTP connection to be closed and prevent it from being reused for1247* subsequent operations.1248*1249* @return A {@code BodySubscriber} which publishes the response body1250* through a {@code Publisher<List<ByteBuffer>>}.1251*/1252public static BodySubscriber<Publisher<List<ByteBuffer>>> ofPublisher() {1253return ResponseSubscribers.createPublisher();1254}12551256/**1257* Returns a response subscriber which discards the response body. The1258* supplied value is the value that will be returned from1259* {@link HttpResponse#body()}.1260*1261* @param <U> the type of the response body1262* @param value the value to return from HttpResponse.body(), may be {@code null}1263* @return a {@code BodySubscriber}1264*/1265public static <U> BodySubscriber<U> replacing(U value) {1266return new ResponseSubscribers.NullSubscriber<>(Optional.ofNullable(value));1267}12681269/**1270* Returns a response subscriber which discards the response body.1271*1272* @return a response body subscriber1273*/1274public static BodySubscriber<Void> discarding() {1275return new ResponseSubscribers.NullSubscriber<>(Optional.ofNullable(null));1276}12771278/**1279* Returns a {@code BodySubscriber} which buffers data before delivering1280* it to the given downstream subscriber. The subscriber guarantees to1281* deliver {@code bufferSize} bytes of data to each invocation of the1282* downstream's {@link BodySubscriber#onNext(Object) onNext} method,1283* except for the final invocation, just before1284* {@link BodySubscriber#onComplete() onComplete} is invoked. The final1285* invocation of {@code onNext} may contain fewer than {@code bufferSize}1286* bytes.1287*1288* <p> The returned subscriber delegates its {@link BodySubscriber#getBody()1289* getBody()} method to the downstream subscriber.1290*1291* @param <T> the type of the response body1292* @param downstream the downstream subscriber1293* @param bufferSize the buffer size1294* @return a buffering body subscriber1295* @throws IllegalArgumentException if {@code bufferSize <= 0}1296*/1297public static <T> BodySubscriber<T> buffering(BodySubscriber<T> downstream,1298int bufferSize) {1299if (bufferSize <= 0)1300throw new IllegalArgumentException("must be greater than 0");1301return new BufferingSubscriber<>(downstream, bufferSize);1302}13031304/**1305* Returns a {@code BodySubscriber} whose response body value is that of1306* the result of applying the given function to the body object of the1307* given {@code upstream} {@code BodySubscriber}.1308*1309* <p> The mapping function is executed using the client's {@linkplain1310* HttpClient#executor() executor}, and can therefore be used to map any1311* response body type, including blocking {@link InputStream}.1312* However, performing any blocking operation in the mapper function1313* runs the risk of blocking the executor's thread for an unknown1314* amount of time (at least until the blocking operation finishes),1315* which may end up starving the executor of available threads.1316* Therefore, in the case where mapping to the desired type might1317* block (e.g. by reading on the {@code InputStream}), then mapping1318* to a {@link java.util.function.Supplier Supplier} of the desired1319* type and deferring the blocking operation until {@link Supplier#get()1320* Supplier::get} is invoked by the caller's thread should be preferred,1321* as shown in the following example which uses a well-known JSON parser to1322* convert an {@code InputStream} into any annotated Java type.1323*1324* <p>For example:1325* <pre> {@code public static <W> BodySubscriber<Supplier<W>> asJSON(Class<W> targetType) {1326* BodySubscriber<InputStream> upstream = BodySubscribers.ofInputStream();1327*1328* BodySubscriber<Supplier<W>> downstream = BodySubscribers.mapping(1329* upstream,1330* (InputStream is) -> () -> {1331* try (InputStream stream = is) {1332* ObjectMapper objectMapper = new ObjectMapper();1333* return objectMapper.readValue(stream, targetType);1334* } catch (IOException e) {1335* throw new UncheckedIOException(e);1336* }1337* });1338* return downstream;1339* } }</pre>1340*1341* @param <T> the upstream body type1342* @param <U> the type of the body subscriber returned1343* @param upstream the body subscriber to be mapped1344* @param mapper the mapping function1345* @return a mapping body subscriber1346*/1347public static <T,U> BodySubscriber<U> mapping(BodySubscriber<T> upstream,1348Function<? super T, ? extends U> mapper)1349{1350return new ResponseSubscribers.MappingSubscriber<>(upstream, mapper);1351}1352}1353}135413551356