src/java.net.http/share/classes/java/net/http/HttpResponse.java
branchhttp-client-branch
changeset 56099 41ba54ac9403
parent 56097 15dc43936d39
child 56119 33436f5e3b9d
equal deleted inserted replaced
56098:e1890248eafe 56099:41ba54ac9403
    58 
    58 
    59 /**
    59 /**
    60  * An HTTP response.
    60  * An HTTP response.
    61  *
    61  *
    62  * <p> An {@code HttpResponse} is not created directly, but rather returned as
    62  * <p> An {@code HttpResponse} is not created directly, but rather returned as
    63  * a result of sending an {@linkplain HttpRequest}. An {@code HttpResponse} is
    63  * a result of sending an {@link HttpRequest}. An {@code HttpResponse} is
    64  * made available when the response status code and headers have been received,
    64  * made available when the response status code and headers have been received,
    65  * and typically after the response body has also been completely received.
    65  * and typically after the response body has also been completely received.
    66  * Whether or not the {@code HttpResponse} is made available before the response
    66  * Whether or not the {@code HttpResponse} is made available before the response
    67  * body has been completely received depends on the {@linkplain BodyHandler
    67  * body has been completely received depends on the {@link BodyHandler
    68  * BodyHandler} provided when sending the {@code HttpRequest}.
    68  * BodyHandler} provided when sending the {@code HttpRequest}.
    69  *
    69  *
    70  * <p> This class provides methods for accessing the response status code,
    70  * <p> This class provides methods for accessing the response status code,
    71  * headers, the response body, and the {@code HttpRequest} corresponding
    71  * headers, the response body, and the {@code HttpRequest} corresponding
    72  * to this response.
    72  * to this response.
   163     /**
   163     /**
   164      * A handler for response bodies.
   164      * A handler for response bodies.
   165      *
   165      *
   166      * <p> The {@code BodyHandler} interface allows inspection of the response
   166      * <p> The {@code BodyHandler} interface allows inspection of the response
   167      * code and headers, before the actual response body is received, and is
   167      * code and headers, before the actual response body is received, and is
   168      * responsible for creating the response {@linkplain BodySubscriber
   168      * responsible for creating the response {@link BodySubscriber
   169      * BodySubscriber}. The {@code BodySubscriber} consumes the actual response
   169      * BodySubscriber}. The {@code BodySubscriber} consumes the actual response
   170      * body bytes and converts them into a higher-level Java type.
   170      * body bytes and converts them into a higher-level Java type.
   171      *
   171      *
   172      * <p> A {@code BodyHandler} is a function that takes two parameters: the
   172      * <p> A {@code BodyHandler} is a function that takes two parameters: the
   173      * response status code and the response headers; and which returns a
   173      * response status code and the response headers; and which returns a
   206      *  client.sendAsync(request, BodyHandler.asFile(Paths.get("/tmp/f")))
   206      *  client.sendAsync(request, BodyHandler.asFile(Paths.get("/tmp/f")))
   207      *        .thenApply(HttpResponse::body)
   207      *        .thenApply(HttpResponse::body)
   208      *        .thenAccept(System.out::println) }</pre>
   208      *        .thenAccept(System.out::println) }</pre>
   209      * Note, that even though these pre-defined handlers do not examine the
   209      * Note, that even though these pre-defined handlers do not examine the
   210      * response code, the response code and headers are always retrievable from
   210      * response code, the response code and headers are always retrievable from
   211      * the {@linkplain HttpResponse}, when it is returned.
   211      * the {@link HttpResponse}, when it is returned.
   212      *
   212      *
   213      * <p> In the second example, the function returns a different subscriber
   213      * <p> In the second example, the function returns a different subscriber
   214      * depending on the status code.
   214      * depending on the status code.
   215      * <pre>{@code   HttpRequest request = HttpRequest.newBuilder()
   215      * <pre>{@code   HttpRequest request = HttpRequest.newBuilder()
   216      *        .uri(URI.create("http://www.foo.com/"))
   216      *        .uri(URI.create("http://www.foo.com/"))
   225      * @param <T> the response body type
   225      * @param <T> the response body type
   226      */
   226      */
   227     @FunctionalInterface
   227     @FunctionalInterface
   228     public interface BodyHandler<T> {
   228     public interface BodyHandler<T> {
   229         /**
   229         /**
   230          * Returns a {@linkplain BodySubscriber BodySubscriber} considering the
   230          * Returns a {@link BodySubscriber BodySubscriber} considering the
   231          * given response status code and headers. This method is invoked before
   231          * given response status code and headers. This method is invoked before
   232          * the actual response body bytes are read and its implementation must
   232          * the actual response body bytes are read and its implementation must
   233          * return a {@code BodySubscriber} to consume the response body bytes.
   233          * return a {@code BodySubscriber} to consume the response body bytes.
   234          *
   234          *
   235          * <p> The response body can be discarded using one of {@linkplain
   235          * <p> The response body can be discarded using one of {@link
   236          * #discard() discard} or {@linkplain #replace(Object) replace}.
   236          * #discard() discard} or {@link #replace(Object) replace}.
   237          *
   237          *
   238          * @param statusCode the HTTP status code received
   238          * @param statusCode the HTTP status code received
   239          * @param responseHeaders the response headers received
   239          * @param responseHeaders the response headers received
   240          * @return a body subscriber
   240          * @return a body subscriber
   241          */
   241          */
   242         public BodySubscriber<T> apply(int statusCode, HttpHeaders responseHeaders);
   242         public BodySubscriber<T> apply(int statusCode, HttpHeaders responseHeaders);
   243 
   243 
   244 
   244 
   245         /**
   245         /**
   246          * Returns a response body handler that returns a {@link BodySubscriber
   246          * Returns a response body handler that returns a {@link BodySubscriber
   247          * BodySubscriber}{@code <Void>} obtained from {@linkplain
   247          * BodySubscriber}{@code <Void>} obtained from {@link
   248          * BodySubscriber#fromSubscriber(Subscriber)}, with the given
   248          * BodySubscriber#fromSubscriber(Subscriber)}, with the given
   249          * {@code subscriber}.
   249          * {@code subscriber}.
   250          *
   250          *
   251          * <p> The response body is not available through this, or the {@code
   251          * <p> The response body is not available through this, or the {@code
   252          * HttpResponse} API, but instead all response body is forwarded to the
   252          * HttpResponse} API, but instead all response body is forwarded to the
   616         /**
   616         /**
   617          * Returns a {@code BodyHandler} which, when invoked, returns a {@linkplain
   617          * Returns a {@code BodyHandler} which, when invoked, returns a {@linkplain
   618          * BodySubscriber#buffering(BodySubscriber,int) buffering BodySubscriber}
   618          * BodySubscriber#buffering(BodySubscriber,int) buffering BodySubscriber}
   619          * that buffers data before delivering it to the downstream subscriber.
   619          * that buffers data before delivering it to the downstream subscriber.
   620          * These {@code BodySubscriber} instances are created by calling
   620          * These {@code BodySubscriber} instances are created by calling
   621          * {@linkplain BodySubscriber#buffering(BodySubscriber,int)
   621          * {@link BodySubscriber#buffering(BodySubscriber,int)
   622          * BodySubscriber.buffering} with a subscriber obtained from the given
   622          * BodySubscriber.buffering} with a subscriber obtained from the given
   623          * downstream handler and the {@code bufferSize} parameter.
   623          * downstream handler and the {@code bufferSize} parameter.
   624          *
   624          *
   625          * @param downstreamHandler the downstream handler
   625          * @param downstreamHandler the downstream handler
   626          * @param bufferSize the buffer size parameter passed to {@linkplain
   626          * @param bufferSize the buffer size parameter passed to {@link
   627          *        BodySubscriber#buffering(BodySubscriber,int) BodySubscriber.buffering}
   627          *        BodySubscriber#buffering(BodySubscriber,int) BodySubscriber.buffering}
   628          * @return a body handler
   628          * @return a body handler
   629          * @throws IllegalArgumentException if {@code bufferSize <= 0}
   629          * @throws IllegalArgumentException if {@code bufferSize <= 0}
   630          */
   630          */
   631          public static <T> BodyHandler<T> buffering(BodyHandler<T> downstreamHandler,
   631          public static <T> BodyHandler<T> buffering(BodyHandler<T> downstreamHandler,
   694          * <p> Entries are added to the given map for each push promise accepted.
   694          * <p> Entries are added to the given map for each push promise accepted.
   695          * The entry's key is the push request, and the entry's value is a
   695          * The entry's key is the push request, and the entry's value is a
   696          * {@code CompletableFuture} that completes with the response
   696          * {@code CompletableFuture} that completes with the response
   697          * corresponding to the key's push request. A push request is rejected /
   697          * corresponding to the key's push request. A push request is rejected /
   698          * cancelled if there is already an entry in the map whose key is
   698          * cancelled if there is already an entry in the map whose key is
   699          * {@linkplain HttpRequest#equals equal} to it. A push request is
   699          * {@link HttpRequest#equals equal} to it. A push request is
   700          * rejected / cancelled if it  does not have the same origin as its
   700          * rejected / cancelled if it  does not have the same origin as its
   701          * initiating request.
   701          * initiating request.
   702          *
   702          *
   703          * <p> Entries are added to the given map as soon as practically
   703          * <p> Entries are added to the given map as soon as practically
   704          * possible when a push promise is received and accepted. That way code,
   704          * possible when a push promise is received and accepted. That way code,
   749      * InputStream}, then it completes before the body has been read, because
   749      * InputStream}, then it completes before the body has been read, because
   750      * the calling code uses the {@code InputStream} to consume the data.
   750      * the calling code uses the {@code InputStream} to consume the data.
   751      *
   751      *
   752      * @apiNote To ensure that all resources associated with the corresponding
   752      * @apiNote To ensure that all resources associated with the corresponding
   753      * HTTP exchange are properly released, an implementation of {@code
   753      * HTTP exchange are properly released, an implementation of {@code
   754      * BodySubscriber} should ensure to {@linkplain Flow.Subscription#request
   754      * BodySubscriber} should ensure to {@link Flow.Subscription#request
   755      * request} more data until one of {@linkplain #onComplete() onComplete} or
   755      * request} more data until one of {@link #onComplete() onComplete} or
   756      * {@link #onError(Throwable) onError} are signalled, or {@linkplain
   756      * {@link #onError(Throwable) onError} are signalled, or {@link
   757      * Flow.Subscription#request cancel} its {@linkplain
   757      * Flow.Subscription#request cancel} its {@linkplain
   758      * #onSubscribe(Flow.Subscription) subscription} if unable or unwilling to
   758      * #onSubscribe(Flow.Subscription) subscription} if unable or unwilling to
   759      * do so. Calling {@code cancel} before exhausting the response body data
   759      * do so. Calling {@code cancel} before exhausting the response body data
   760      * may cause the underlying HTTP connection to be closed and prevent it
   760      * may cause the underlying HTTP connection to be closed and prevent it
   761      * from being reused for subsequent operations.
   761      * from being reused for subsequent operations.
   822             return new ResponseSubscribers.SubscriberAdapter<S,T>(subscriber, finisher);
   822             return new ResponseSubscribers.SubscriberAdapter<S,T>(subscriber, finisher);
   823         }
   823         }
   824 
   824 
   825         /**
   825         /**
   826          * Returns a body subscriber that forwards all response body to the
   826          * Returns a body subscriber that forwards all response body to the
   827          * given {@code Flow.Subscriber}, lines by lines.
   827          * given {@code Flow.Subscriber}, line by line.
   828          * The {@linkplain #getBody() completion
   828          * The {@linkplain #getBody() completion
   829          * stage} of the returned body subscriber completes after one of the
   829          * stage} of the returned body subscriber completes after one of the
   830          * given subscribers {@code onComplete} or {@code onError} has been
   830          * given subscribers {@code onComplete} or {@code onError} has been
   831          * invoked.
   831          * invoked.
   832          * Bytes are decoded using the {@linkplain StandardCharsets#UTF_8
   832          * Bytes are decoded using the {@link StandardCharsets#UTF_8
   833          * UTF-8} charset, and lines are delimited in the manner of
   833          * UTF-8} charset, and lines are delimited in the manner of
   834          * {@link BufferedReader#readLine()}.
   834          * {@link BufferedReader#readLine()}.
   835          *
   835          *
   836          * @apiNote This method can be used as an adapter between {@code
   836          * @apiNote This method can be used as an adapter between {@code
   837          * BodySubscriber} and {@code Flow.Subscriber}.
   837          * BodySubscriber} and {@code Flow.Subscriber}.
   850                     StandardCharsets.UTF_8, null);
   850                     StandardCharsets.UTF_8, null);
   851         }
   851         }
   852 
   852 
   853         /**
   853         /**
   854          * Returns a body subscriber that forwards all response body to the
   854          * Returns a body subscriber that forwards all response body to the
   855          * given {@code Flow.Subscriber}, lines by lines.
   855          * given {@code Flow.Subscriber}, line by line. The {@linkplain #getBody()
   856          * The {@linkplain #getBody() completion
   856          * completion stage} of the returned body subscriber completes after
   857          * stage} of the returned body subscriber completes after one of the
   857          * one of the given subscribers {@code onComplete} or {@code onError}
   858          * given subscribers {@code onComplete} or {@code onError} has been
   858          * has been invoked.
   859          * invoked.
       
   860          *
   859          *
   861          * <p> The given {@code finisher} function is applied after the given
   860          * <p> The given {@code finisher} function is applied after the given
   862          * subscriber's {@code onComplete} has been invoked. The {@code finisher}
   861          * subscriber's {@code onComplete} has been invoked. The {@code finisher}
   863          * function is invoked with the given subscriber, and returns a value
   862          * function is invoked with the given subscriber, and returns a value
   864          * that is set as the response's body.
   863          * that is set as the response's body.
  1079 
  1078 
  1080         /**
  1079         /**
  1081          * Returns a {@code BodySubscriber} which buffers data before delivering
  1080          * Returns a {@code BodySubscriber} which buffers data before delivering
  1082          * it to the given downstream subscriber. The subscriber guarantees to
  1081          * it to the given downstream subscriber. The subscriber guarantees to
  1083          * deliver {@code buffersize} bytes of data to each invocation of the
  1082          * deliver {@code buffersize} bytes of data to each invocation of the
  1084          * downstream's {@linkplain #onNext(Object) onNext} method, except for
  1083          * downstream's {@link #onNext(Object) onNext} method, except for
  1085          * the final invocation, just before {@linkplain #onComplete() onComplete}
  1084          * the final invocation, just before {@link #onComplete() onComplete}
  1086          * is invoked. The final invocation of {@code onNext} may contain fewer
  1085          * is invoked. The final invocation of {@code onNext} may contain fewer
  1087          * than {@code buffersize} bytes.
  1086          * than {@code bufferSize} bytes.
  1088          *
  1087          *
  1089          * <p> The returned subscriber delegates its {@link #getBody()} method
  1088          * <p> The returned subscriber delegates its {@link #getBody()} method
  1090          * to the downstream subscriber.
  1089          * to the downstream subscriber.
  1091          *
  1090          *
  1092          * @param downstream the downstream subscriber
  1091          * @param downstream the downstream subscriber
  1105          * Returns a {@code BodySubscriber} whose response body value is that of
  1104          * Returns a {@code BodySubscriber} whose response body value is that of
  1106          * the result of applying the given function to the body object of the
  1105          * the result of applying the given function to the body object of the
  1107          * given {@code upstream} {@code BodySubscriber}.
  1106          * given {@code upstream} {@code BodySubscriber}.
  1108          *
  1107          *
  1109          * <p> The mapping function is executed using the client's {@linkplain
  1108          * <p> The mapping function is executed using the client's {@linkplain
  1110          * HttpClient#executor()}, and can therefore be used to map any response
  1109          * HttpClient#executor() executor}, and can therefore be used to map any
  1111          * body type, including blocking {@linkplain InputStream}, as shown in
  1110          * response body type, including blocking {@link InputStream}, as shown
  1112          * the following example which uses a well-known JSON parser to convert
  1111          * in the following example which uses a well-known JSON parser to
  1113          * an {@code InputStream} into any annotated Java object type.
  1112          * convert an {@code InputStream} into any annotated Java type.
  1114          *
  1113          *
  1115          * <p>For example:
  1114          * <p>For example:
  1116          * <pre> {@code  public static <W> BodySubscriber<W> asJSON(Class<W> targetType) {
  1115          * <pre> {@code  public static <W> BodySubscriber<W> asJSON(Class<W> targetType) {
  1117          *     BodySubscriber<InputStream> upstream = BodySubscriber.asInputStream();
  1116          *     BodySubscriber<InputStream> upstream = BodySubscriber.asInputStream();
  1118          *
  1117          *