/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.net.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.OpenOption; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Flow; import java.util.concurrent.Flow.Subscriber; import java.util.concurrent.Flow.Publisher; import java.util.concurrent.Flow.Subscription; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import javax.net.ssl.SSLSession; import jdk.internal.net.http.BufferingSubscriber; import jdk.internal.net.http.LineSubscriberAdapter; import jdk.internal.net.http.ResponseBodyHandlers.FileDownloadBodyHandler; import jdk.internal.net.http.ResponseBodyHandlers.PathBodyHandler; import jdk.internal.net.http.ResponseBodyHandlers.PushPromisesHandlerWithMap; import jdk.internal.net.http.ResponseSubscribers; import jdk.internal.net.http.ResponseSubscribers.PathSubscriber; import static java.nio.file.StandardOpenOption.*; import static jdk.internal.net.http.common.Utils.charsetFrom; /** * An HTTP response. * *
An {@code HttpResponse} is not created directly, but rather returned as * a result of sending an {@link HttpRequest}. An {@code HttpResponse} is * made available when the response status code and headers have been received, * and typically after the response body has also been completely received. * Whether or not the {@code HttpResponse} is made available before the response * body has been completely received depends on the {@link BodyHandler * BodyHandler} provided when sending the {@code HttpRequest}. * *
This class provides methods for accessing the response status code, * headers, the response body, and the {@code HttpRequest} corresponding * to this response. * *
The following is an example of retrieving a response as a String: * *
{@code HttpResponse response = client
* .send(request, BodyHandlers.ofString()); }
*
* The class {@link BodyHandlers BodyHandlers} provides implementations
* of many common response handlers. Alternatively, a custom {@code BodyHandler}
* implementation can be used.
*
* @param The returned {@code HttpRequest} may not be the initiating request
* provided when {@linkplain HttpClient#send(HttpRequest, BodyHandler)
* sending}. For example, if the initiating request was redirected, then the
* request returned by this method will have the redirected URI, which will
* be different from the initiating request URI.
*
* @see #previousResponse()
*
* @return the request
*/
public HttpRequest request();
/**
* Returns an {@code Optional} containing the previous intermediate response
* if one was received. An intermediate response is one that is received
* as a result of redirection or authentication. If no previous response
* was received then an empty {@code Optional} is returned.
*
* @return an Optional containing the HttpResponse, if any.
*/
public Optional If this {@code HttpResponse} was returned from an invocation of
* {@link #previousResponse()} then this method returns {@code null}
*
* @return the body
*/
public T body();
/**
* Returns an {@link Optional} containing the {@link SSLSession} in effect
* for this response. Returns an empty {@code Optional} if this is not a
* HTTPS response.
*
* @return an {@code Optional} containing the {@code SSLSession} associated
* with the response
*/
public Optional The {@code BodyHandler} interface allows inspection of the response
* code and headers, before the actual response body is received, and is
* responsible for creating the response {@link BodySubscriber
* BodySubscriber}. The {@code BodySubscriber} consumes the actual response
* body bytes and, typically, converts them into a higher-level Java type.
*
* A {@code BodyHandler} is a function that takes a {@link ResponseInfo
* ResponseInfo} object; and which returns a {@code BodySubscriber}. The
* {@code 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 {@linkplain BodyHandlers
* predefined body handlers} that always process the response body in the
* same way ( streams the response body to a file ).
*
* In the second example, the function returns a different subscriber
* depending on the status code.
* The response body can be discarded using one of {@link
* BodyHandlers#discarding() discarding} or {@link
* BodyHandlers#replacing(Object) replacing}.
*
* @param responseInfo the response info
* @return a body subscriber
*/
public BodySubscriber These implementations do not examine the status code, meaning the
* body is always accepted. They typically return an equivalently named
* {@code BodySubscriber}. Alternatively, a custom handler can be used to
* examine the status code and headers, and return a different body
* subscriber, of the same type, as appropriate.
*
* The following are examples of using the predefined body handlers to
* convert a flow of response body data into common high-level Java objects:
*
* The response body is not available through this, or the {@code
* HttpResponse} API, but instead all response body is forwarded to the
* given {@code subscriber}, which should make it available, if
* appropriate, through some other mechanism, e.g. an entry in a
* database, etc.
*
* @apiNote This method can be used as an adapter between {@code
* BodySubscriber} and {@code Flow.Subscriber}.
*
* For example:
* The given {@code finisher} function is applied after the given
* subscriber's {@code onComplete} has been invoked. The {@code finisher}
* function is invoked with the given subscriber, and returns a value
* that is set as the response's body.
*
* @apiNote This method can be used as an adapter between {@code
* BodySubscriber} and {@code Flow.Subscriber}.
*
* For example:
* The response body is not available through this, or the {@code
* HttpResponse} API, but instead all response body is forwarded to the
* given {@code subscriber}, which should make it available, if
* appropriate, through some other mechanism, e.g. an entry in a
* database, etc.
*
* @apiNote This method can be used as an adapter between a {@code
* BodySubscriber} and a text based {@code Flow.Subscriber} that parses
* text line by line.
*
* For example:
* The given {@code finisher} function is applied after the given
* subscriber's {@code onComplete} has been invoked. The {@code finisher}
* function is invoked with the given subscriber, and returns a value
* that is set as the response's body.
*
* @apiNote This method can be used as an adapter between a {@code
* BodySubscriber} and a text based {@code Flow.Subscriber} that parses
* text line by line.
*
* For example:
* When the {@code HttpResponse} object is returned, the body has
* been completely written to the file, and {@link #body()} returns a
* reference to its {@link Path}.
*
* Security manager permission checks are performed in this factory
* method, when the {@code BodyHandler} is created. Care must be taken
* that the {@code BodyHandler} is not shared with untrusted code.
*
* @param file the file to store the body in
* @param openOptions any options to use when opening/creating the file
* @return a response body handler
* @throws IllegalArgumentException if an invalid set of open options
* are specified
* @throws SecurityException If a security manager has been installed
* and it denies {@linkplain SecurityManager#checkWrite(String)
* write access} to the file.
*/
public static BodyHandler Equivalent to: {@code ofFile(file, CREATE, WRITE)}
*
* Security manager permission checks are performed in this factory
* method, when the {@code BodyHandler} is created. Care must be taken
* that the {@code BodyHandler} is not shared with untrusted code.
*
* @param file the file to store the body in
* @return a response body handler
* @throws SecurityException If a security manager has been installed
* and it denies {@linkplain SecurityManager#checkWrite(String)
* write access} to the file.
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the body has
* been completely written to the file and {@link #body()} returns a
* {@code Path} object for the file. The returned {@code Path} is the
* combination of the supplied directory name and the file name supplied
* by the server. If the destination directory does not exist or cannot
* be written to, then the response will fail with an {@link IOException}.
*
* Security manager permission checks are performed in this factory
* method, when the {@code BodyHandler} is created. Care must be taken
* that the {@code BodyHandler} is not shared with untrusted code.
*
* @param directory the directory to store the file in
* @param openOptions open options used when opening the file
* @return a response body handler
* @throws IllegalArgumentException if the given path does not exist,
* is not a directory, is not writable, or if an invalid set
* of open options are specified
* @throws SecurityException If a security manager has been installed
* and it denies
* {@linkplain SecurityManager#checkRead(String) read access}
* to the directory, or it denies
* {@linkplain SecurityManager#checkWrite(String) write access}
* to the directory, or it denies
* {@linkplain SecurityManager#checkWrite(String) write access}
* to the files within the directory.
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the response
* headers will have been completely read, but the body may not have
* been fully received yet. The {@link #body()} method returns an
* {@link InputStream} from which the body can be read as it is received.
*
* @apiNote See {@link BodySubscribers#ofInputStream()} for more
* information.
*
* @return a response body handler
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the body may
* not have been completely received.
*
* @return a response body handler
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the body has
* been completely written to the consumer.
*
* @apiNote
* The subscriber returned by this handler is not flow controlled.
* Therefore, the supplied consumer must be able to process whatever
* amount of data is delivered in a timely fashion.
*
* @param consumer a Consumer to accept the response body
* @return a response body handler
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the body has
* been completely written to the byte array.
*
* @return a response body handler
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the body has
* been completely written to the string.
*
* @return a response body handler
*/
public static BodyHandler When the {@code HttpResponse} object is returned, the response
* headers will have been completely read, but the body may not have
* been fully received yet. The {@link #body()} method returns a
* {@link Publisher Publisher}{@code A push promise is a synthetic request sent by an HTTP/2 server
* when retrieving an initiating client-sent request. The server has
* determined, possibly through inspection of the initiating request, that
* the client will likely need the promised resource, and hence pushes a
* synthetic push request, in the form of a push promise, to the client. The
* client can choose to accept or reject the push promise request.
*
* A push promise request may be received up to the point where the
* response body of the initiating client-sent request has been fully
* received. The delivery of a push promise response, however, is not
* coordinated with the delivery of the response to the initiating
* client-sent request.
*
* @param This method is invoked once for each push promise received, up
* to the point where the response body of the initiating client-sent
* request has been fully received.
*
* A push promise is accepted by invoking the given {@code acceptor}
* function. The {@code acceptor} function must be passed a non-null
* {@code BodyHandler}, that is to be used to handle the promise's
* response body. The acceptor function will return a {@code
* CompletableFuture} that completes with the promise's response.
*
* If the {@code acceptor} function is not successfully invoked,
* then the push promise is rejected. The {@code acceptor} function will
* throw an {@code IllegalStateException} if invoked more than once.
*
* @param initiatingRequest the initiating client-send request
* @param pushPromiseRequest the synthetic push request
* @param acceptor the acceptor function that must be successfully
* invoked to accept the push promise
*/
public void applyPushPromise(
HttpRequest initiatingRequest,
HttpRequest pushPromiseRequest,
Function Entries are added to the given map for each push promise accepted.
* The entry's key is the push request, and the entry's value is a
* {@code CompletableFuture} that completes with the response
* corresponding to the key's push request. A push request is rejected /
* cancelled if there is already an entry in the map whose key is
* {@linkplain HttpRequest#equals equal} to it. A push request is
* rejected / cancelled if it does not have the same origin as its
* initiating request.
*
* Entries are added to the given map as soon as practically
* possible when a push promise is received and accepted. That way code,
* using such a map like a cache, can determine if a push promise has
* been issued by the server and avoid making, possibly, unnecessary
* requests.
*
* The delivery of a push promise response is not coordinated with
* the delivery of the response to the initiating client-sent request.
* However, when the response body for the initiating client-sent
* request has been fully received, the map is guaranteed to be fully
* populated, that is, no more entries will be added. The individual
* {@code CompletableFutures} contained in the map may or may not
* already be completed at this point.
*
* @param The object acts as a {@link Flow.Subscriber}<{@link List}<{@link
* ByteBuffer}>> to the HTTP Client implementation, which publishes
* lists of ByteBuffers containing the response body. The Flow of data, as
* well as the order of ByteBuffers in the Flow lists, is a strictly ordered
* representation of the response body. Both the Lists and the ByteBuffers,
* once passed to the subscriber, are no longer used by the HTTP Client. The
* subscriber converts the incoming buffers of data to some higher-level
* Java type {@code T}.
*
* The {@link #getBody()} method returns a
* {@link CompletionStage}{@code The following are examples of using the predefined body subscribers
* to convert a flow of response body data into common high-level Java
* objects:
*
* The given {@code finisher} function is applied after the given
* subscriber's {@code onComplete} has been invoked. The {@code finisher}
* function is invoked with the given subscriber, and returns a value
* that is set as the response's body.
*
* @apiNote This method can be used as an adapter between {@code
* BodySubscriber} and {@code Flow.Subscriber}.
*
* @param The given {@code finisher} function is applied after the given
* subscriber's {@code onComplete} has been invoked. The {@code finisher}
* function is invoked with the given subscriber, and returns a value
* that is set as the response's body.
*
* @apiNote This method can be used as an adapter between {@code
* BodySubscriber} and {@code Flow.Subscriber}.
*
* @param The {@link HttpResponse} using this subscriber is available after
* the entire response has been read.
*
* @param charset the character set to convert the String with
* @return a body subscriber
*/
public static BodySubscriber The {@link HttpResponse} using this subscriber is available after
* the entire response has been read.
*
* @return a body subscriber
*/
public static BodySubscriber The {@link HttpResponse} using this subscriber is available after
* the entire response has been read.
*
* Security manager permission checks are performed in this factory
* method, when the {@code BodySubscriber} is created. Care must be taken
* that the {@code BodyHandler} is not shared with untrusted code.
*
* @param file the file to store the body in
* @param openOptions the list of options to open the file with
* @return a body subscriber
* @throws IllegalArgumentException if an invalid set of open options
* are specified
* @throws SecurityException if a security manager has been installed
* and it denies {@linkplain SecurityManager#checkWrite(String)
* write access} to the file
*/
public static BodySubscriber Equivalent to: {@code ofFile(file, CREATE, WRITE)}
*
* Security manager permission checks are performed in this factory
* method, when the {@code BodySubscriber} is created. Care must be taken
* that the {@code BodyHandler} is not shared with untrusted code.
*
* @param file the file to store the body in
* @return a body subscriber
* @throws SecurityException if a security manager has been installed
* and it denies {@linkplain SecurityManager#checkWrite(String)
* write access} to the file
*/
public static BodySubscriber The {@link HttpResponse} using this subscriber is available after
* the entire response has been read.
*
* @apiNote
* 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.
*
* @param consumer a Consumer of byte arrays
* @return a BodySubscriber
*/
public static BodySubscriber The {@link HttpResponse} using 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 the {@link InputStream}.
*
* @apiNote 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
* {@link InputStream#close} if it is unable or unwilling to do so.
* Calling {@code close} before exhausting the stream may cause
* the underlying HTTP connection to be closed and prevent it
* from being reused for subsequent operations.
*
* @return a body subscriber that streams the response body as an
* {@link InputStream}.
*/
public static BodySubscriber The {@link HttpResponse} using 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 the {@link Stream}.
*
* @apiNote 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 {@link Stream#close} if it is unable or unwilling to do so.
* Calling {@code close} before exhausting the stream may cause
* the underlying HTTP connection to be closed and prevent it
* from being reused for subsequent operations.
*
* @param charset the character set to use when converting bytes to characters
* @return a body subscriber that streams the response body as a
* {@link Stream Stream}{@code The {@link HttpResponse} using 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 the {@code HttpResponse} {@link HttpResponse#body() body}
* method.
*
* The publisher returned by the {@link HttpResponse#body() body}
* method 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 their
* {@link Subscriber#onError(Throwable) onError} method
* will be invoked with an {@code IllegalStateException}.
*
* @apiNote 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
* {@linkplain Subscription#request(long) requests} all bytes
* until {@link Subscriber#onComplete() onComplete} or
* {@link Subscriber#onError(Throwable) onError} are invoked, or
* cancel the provided {@linkplain Subscriber#onSubscribe(Subscription)
* subscription} if it is unable or unwilling to do so.
* Note that depending on the actual HTTP protocol {@linkplain
* HttpClient.Version 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.
*
* @return A {@code BodySubscriber} which publishes the response body
* through a {@code Publisher The returned subscriber delegates its {@link BodySubscriber#getBody()
* getBody()} method to the downstream subscriber.
*
* @param The mapping function is executed using the client's {@linkplain
* HttpClient#executor() executor}, and can therefore be used to map any
* response body type, including blocking {@link 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 the {@code InputStream}), then mapping
* to a {@link java.util.function.Supplier Supplier} of the desired
* type and deferring the blocking operation until {@link Supplier#get()
* Supplier::get} is invoked by the caller's thread should be preferred,
* as shown in the following example which uses a well-known JSON parser to
* convert an {@code InputStream} into any annotated Java type.
*
* For example:
* {@code 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); }
*
* Note, that even though the pre-defined handlers do not examine the
* response code, the response code and headers are always retrievable from
* the {@link HttpResponse}, when it is returned.
*
* {@code HttpRequest request = HttpRequest.newBuilder()
* .uri(URI.create("http://www.foo.com/"))
* .build();
* BodyHandler
*
* @param {@code // Receives the response body as a String
* HttpResponse
*
* @since 11
*/
public static class BodyHandlers {
private BodyHandlers() { }
/**
* Returns a response body handler that returns a {@link BodySubscriber
* BodySubscriber}{@code {@code TextSubscriber subscriber = new TextSubscriber();
* HttpResponse
*
* @param subscriber the subscriber
* @return a response body handler
*/
public static BodyHandler {@code TextSubscriber subscriber = ...; // accumulates bytes and transforms them into a String
* HttpResponse
*
* @param the type of the Subscriber
* @param >,T> BodyHandler {@code // A PrintSubscriber that implements Flow.Subscriber
*
* @param subscriber the subscriber
* @return a response body handler
*/
public static BodyHandler {@code // A LineParserSubscriber that implements Flow.Subscriber
*
*
* @param > response = client.send(request,
* BodyHandlers.fromLineSubscriber(subscriber, s -> s.getMatchingLines(), "\n"));
* if (response.statusCode() != 200) {
* System.err.printf("ERROR: %d status received%n", response.statusCode());
* } }
the type of the Subscriber
* @param ,T> BodyHandler>} from which the body
* response bytes can be obtained as they are received. The publisher
* can and must be subscribed to only once.
*
* @apiNote See {@link BodySubscribers#ofPublisher()} for more
* information.
*
* @return a response body handler
*/
public static BodyHandler
> {
/**
* Returns a {@code CompletionStage} which when completed will return
* the response body object. This method can be called at any time
* relative to the other {@link Flow.Subscriber} methods and is invoked
* using the client's {@link HttpClient#executor() executor}.
*
* @return a CompletionStage for the response body
*/
public CompletionStage
{@code // Streams the response body to a File
* HttpResponse
*
* @since 11
*/
public static class BodySubscribers {
private BodySubscribers() { }
/**
* Returns a body subscriber that forwards all response body to the
* given {@code Flow.Subscriber}. The {@linkplain BodySubscriber#getBody()
* completion stage} of the returned body subscriber completes after one
* of the given subscribers {@code onComplete} or {@code onError} has
* been invoked.
*
* @apiNote This method can be used as an adapter between {@code
* BodySubscriber} and {@code Flow.Subscriber}.
*
* @param subscriber the subscriber
* @return a body subscriber
*/
public static BodySubscriber the type of the Subscriber
* @param >,T> BodySubscriber{@code
* fromLineSubscriber(subscriber, s -> null, StandardCharsets.UTF_8, null)
* }
*
* @param subscriber the subscriber
* @return a body subscriber
*/
public static BodySubscriber the type of the Subscriber
* @param ,T> BodySubscriber>}.
*
*
>}.
*/
public static BodySubscriber
{@code public static
*
* @param