50 import static java.nio.charset.StandardCharsets.UTF_8; |
50 import static java.nio.charset.StandardCharsets.UTF_8; |
51 |
51 |
52 /** |
52 /** |
53 * An HTTP request. |
53 * An HTTP request. |
54 * |
54 * |
55 * <p> An {@code HttpRequest} instance is built through a {@code HttpRequest} |
55 * <p> An {@code HttpRequest} instance is built through an {@code HttpRequest} |
56 * {@linkplain HttpRequest.Builder builder}. An {@code HttpRequest} builder |
56 * {@linkplain HttpRequest.Builder builder}. An {@code HttpRequest} builder |
57 * is obtained from one of the {@link HttpRequest#newBuilder(URI) newBuilder} |
57 * is obtained from one of the {@linkplain HttpRequest#newBuilder(URI) newBuilder} |
58 * methods. A request's {@linkplain URI}, headers, and body can be set. Request |
58 * methods. A request's {@linkplain URI}, headers, and body can be set. Request |
59 * bodies are provided through a {@link BodyPublisher} object supplied to the |
59 * bodies are provided through a {@linkplain BodyPublisher BodyPublisher} |
60 * {@link Builder#DELETE(BodyPublisher) DELETE}, |
60 * supplied to one of the {@linkplain Builder#DELETE(BodyPublisher) DELETE}, |
61 * {@link Builder#POST(BodyPublisher) POST} or |
61 * {@linkplain Builder#POST(BodyPublisher) POST} or |
62 * {@link Builder#PUT(BodyPublisher) PUT} methods. |
62 * {@linkplain Builder#PUT(BodyPublisher) PUT} methods. |
63 * Once all required parameters have been set in the builder, {@link |
63 * Once all required parameters have been set in the builder, {@link |
64 * Builder#build() build} will return the {@code HttpRequest}. Builders can be |
64 * Builder#build() build} will return the {@code HttpRequest}. Builders can be |
65 * copied and modified many times in order to build multiple related requests |
65 * copied and modified many times in order to build multiple related requests |
66 * that differ in some parameters. |
66 * that differ in some parameters. |
67 * |
67 * |
68 * <p> <b>Example HTTP interactions:</b> |
68 * <p><b>Example:</b> GET request that prints the response body as a String |
69 * <pre>{@code // GET |
69 * <pre>{@code HttpClient client = HttpClient.newHttpClient(); |
70 * HttpResponse<String> response = client.send( |
70 * HttpRequest request = HttpRequest.newBuilder() |
71 * HttpRequest.newBuilder(new URI("http://www.foo.com/")) |
71 * .uri(URI.create("http://foo.com/")) |
72 * .headers("Foo", "foovalue", "Bar", "barvalue") |
72 * .build(); |
73 * .GET() |
73 * client.sendAsync(request, BodyHandler.asString()) |
74 * .build(), |
74 * .thenApply(HttpResponse::body) |
75 * BodyHandler.asString() |
75 * .thenAccept(System.out::println) |
76 * ); |
76 * .join(); }</pre> |
77 * int statusCode = response.statusCode(); |
77 * |
78 * String body = response.body(); |
78 * <p><b>Request bodies</b> |
79 * |
|
80 * // POST |
|
81 * HttpResponse<Path> response = client.send( |
|
82 * HttpRequest.newBuilder(new URI("http://www.foo.com/")) |
|
83 * .headers("Foo", "foovalue", "Bar", "barvalue") |
|
84 * .POST(BodyPublisher.fromString("Hello world")) |
|
85 * .build(), |
|
86 * BodyHandler.asFile(Paths.get("/path")) |
|
87 * ); |
|
88 * int statusCode = response.statusCode(); |
|
89 * Path body = response.body(); // should be "/path" }</pre> |
|
90 * |
|
91 * <p> The request is sent and the response obtained by invoking one of the |
|
92 * following methods in {@link HttpClient}. |
|
93 * <ul><li>{@link HttpClient#send(HttpRequest, BodyHandler)} blocks |
|
94 * until the entire request has been sent and the response has been received.</li> |
|
95 * <li>{@link HttpClient#sendAsync(HttpRequest, BodyHandler)} sends the |
|
96 * request and receives the response asynchronously. Returns immediately with a |
|
97 * {@linkplain CompletableFuture CompletableFuture}<{@linkplain HttpResponse}>.</li> |
|
98 * </ul> |
|
99 * |
|
100 * <p> Once a {@link HttpResponse} is received, the headers, response code, |
|
101 * and body (typically) are available. Whether the response body bytes has been |
|
102 * read or not depends on the type {@code <T>} of the response body. See below. |
|
103 * |
|
104 * <p> <b>Request bodies</b> |
|
105 * |
79 * |
106 * <p> Request bodies can be sent using one of the convenience request publisher |
80 * <p> Request bodies can be sent using one of the convenience request publisher |
107 * implementations, provided in {@link BodyPublisher}. Alternatively, a custom |
81 * implementations, provided in {@linkplain BodyPublisher BodyPublisher}. |
108 * Publisher implementation can be used. |
|
109 * <ul> |
82 * <ul> |
110 * <li>{@link BodyPublisher#fromByteArray(byte[]) fromByteArray(byte[])} from byte array</li> |
83 * <li>{@link BodyPublisher#fromByteArray(byte[]) fromByteArray(byte[])} from byte array</li> |
111 * <li>{@link BodyPublisher#fromByteArrays(Iterable) fromByteArrays(Iterable)} |
84 * <li>{@link BodyPublisher#fromByteArrays(Iterable) fromByteArrays(Iterable)} |
112 * from an Iterable of byte arrays</li> |
85 * from an Iterable of byte arrays</li> |
113 * <li>{@link BodyPublisher#fromFile(java.nio.file.Path) fromFile(Path)} from the file located |
86 * <li>{@link BodyPublisher#fromFile(java.nio.file.Path) fromFile(Path)} from the file located |
116 * <li>{@link BodyPublisher#fromInputStream(Supplier) fromInputStream}({@link Supplier}< |
89 * <li>{@link BodyPublisher#fromInputStream(Supplier) fromInputStream}({@link Supplier}< |
117 * {@link InputStream}>) from an InputStream obtained from a Supplier</li> |
90 * {@link InputStream}>) from an InputStream obtained from a Supplier</li> |
118 * <li>{@link BodyPublisher#noBody() noBody()} no request body is sent</li> |
91 * <li>{@link BodyPublisher#noBody() noBody()} no request body is sent</li> |
119 * </ul> |
92 * </ul> |
120 * |
93 * |
121 * <p> <b>Response bodies</b> |
94 * <p> Alternatively, a custom {@code BodyPublisher} implementation can be used. |
122 * |
|
123 * <p> Responses bodies are handled at two levels. When sending the request, |
|
124 * a response {@linkplain BodyHandler body handler} is specified. This is a |
|
125 * function that will be called with the response status code and headers, once |
|
126 * they are received. This function must to return a {@link |
|
127 * HttpResponse.BodySubscriber}{@code <T>} which is used to read the response |
|
128 * body bytes, converting them into an instance of {@code T}. After this occurs, |
|
129 * the response becomes available in a {@link HttpResponse}, and the {@link |
|
130 * HttpResponse#body()} can be invoked to obtain the actual body. Some |
|
131 * implementations and examples of usage of both {@link |
|
132 * HttpResponse.BodySubscriber} and {@link HttpResponse.BodyHandler} are |
|
133 * provided in {@link HttpResponse}: |
|
134 * |
|
135 * <p> <b>Some of the pre-defined body handlers</b><br> |
|
136 * <ul> |
|
137 * <li>{@link BodyHandler#asByteArray() BodyHandler.asByteArray()} |
|
138 * stores the body in a byte array</li> |
|
139 * <li>{@link BodyHandler#asString() BodyHandler.asString()} |
|
140 * stores the body as a String </li> |
|
141 * <li>{@link BodyHandler#asFile(java.nio.file.Path) |
|
142 * BodyHandler.asFile(Path)} stores the body in a named file</li> |
|
143 * <li>{@link BodyHandler#replace(Object) BodyHandler.replace(Objectt)} |
|
144 * discards the response body and returns the given replacement value instead.</li> |
|
145 * </ul> |
|
146 * |
|
147 * <p> <b>Blocking/asynchronous behavior and thread usage</b> |
|
148 * |
|
149 * <p> There are two styles of request sending: <i>synchronous</i> and |
|
150 * <i>asynchronous</i>. {@link HttpClient#send(HttpRequest, HttpResponse.BodyHandler) } |
|
151 * blocks the calling thread until the request has been sent and the response received. |
|
152 * |
|
153 * <p> {@link HttpClient#sendAsync(HttpRequest, HttpResponse.BodyHandler)} is |
|
154 * asynchronous and returns immediately with a {@link CompletableFuture}<{@link |
|
155 * HttpResponse}> and when this object completes (possibly in a different |
|
156 * thread) the response has been received. |
|
157 * |
|
158 * <p> Instances of {@code CompletableFuture} can be combined in different ways |
|
159 * to declare the dependencies among several asynchronous tasks, while allowing |
|
160 * for the maximum level of parallelism to be utilized. |
|
161 * |
|
162 * <p> <a id="securitychecks"></a><b>Security checks</b></a> |
|
163 * |
|
164 * <p> If a security manager is present then security checks are performed by |
|
165 * the HTTP Client's sending methods. An appropriate {@link URLPermission} is |
|
166 * required to access the destination server, and proxy server if one has |
|
167 * been configured. The {@code URLPermission} form used to access proxies uses a |
|
168 * method parameter of {@code "CONNECT"} (for all kinds of proxying) and a URL |
|
169 * string of the form {@code "socket://host:port"} where host and port specify |
|
170 * the proxy's address. |
|
171 * |
|
172 * <p> In this implementation, if an explicit {@linkplain |
|
173 * HttpClient.Builder#executor(Executor) executor} has not been set for an |
|
174 * {@code HttpClient}, and a security manager has been installed, then the |
|
175 * default executor will execute asynchronous and dependent tasks in a context |
|
176 * that is granted no permissions. Custom {@linkplain HttpRequest.BodyPublisher |
|
177 * request body publishers}, {@linkplain HttpResponse.BodyHandler response body |
|
178 * handlers}, {@linkplain HttpResponse.BodySubscriber response body subscribers}, |
|
179 * and {@linkplain WebSocket.Listener WebSocket Listeners}, if executing |
|
180 * operations that require privileges, should do so within an appropriate |
|
181 * {@linkplain AccessController#doPrivileged(PrivilegedAction) privileged context}. |
|
182 * |
|
183 * <p> <b>Examples</b> |
|
184 * <pre>{@code HttpClient client = HttpClient.newHttpClient(); |
|
185 * |
|
186 * HttpRequest request = HttpRequest |
|
187 * .newBuilder(URI.create("http://www.foo.com/")) |
|
188 * .POST(BodyPublisher.fromString("Hello world")) |
|
189 * .build(); |
|
190 * |
|
191 * HttpResponse<Path> response = |
|
192 * client.send(request, BodyHandler.asFile(Paths.get("/path"))); |
|
193 * |
|
194 * Path body = response.body(); }</pre> |
|
195 * |
|
196 * <p><b>Asynchronous Example</b> |
|
197 * |
|
198 * <p> The above example will work asynchronously, if {@link HttpClient#sendAsync |
|
199 * (HttpRequest, HttpResponse.BodyHandler) sendAsync} is used instead of |
|
200 * {@link HttpClient#send(HttpRequest,HttpResponse.BodyHandler) send} |
|
201 * in which case the returned object is a {@link CompletableFuture}{@code <HttpResponse>} |
|
202 * instead of {@link HttpResponse}. The following example shows how multiple requests |
|
203 * can be sent asynchronously. It also shows how dependent asynchronous operations |
|
204 * (receiving response, and receiving response body) can be chained easily using |
|
205 * one of the many methods in {@code CompletableFuture}. |
|
206 * <pre>{@code // fetch a list of target URIs asynchronously and store them in Files. |
|
207 * |
|
208 * List<URI> targets = ... |
|
209 * |
|
210 * List<CompletableFuture<File>> futures = targets |
|
211 * .stream() |
|
212 * .map(target -> client |
|
213 * .sendAsync( |
|
214 * HttpRequest.newBuilder(target) |
|
215 * .GET() |
|
216 * .build(), |
|
217 * BodyHandler.asFile(Paths.get("base", target.getPath()))) |
|
218 * .thenApply(response -> response.body()) |
|
219 * .thenApply(path -> path.toFile())) |
|
220 * .collect(Collectors.toList()); |
|
221 * |
|
222 * // all async operations waited for here |
|
223 * |
|
224 * CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])) |
|
225 * .join(); |
|
226 * |
|
227 * // all elements of futures have completed and can be examined. |
|
228 * // Use File.exists() to check whether file was successfully downloaded }</pre> |
|
229 * |
95 * |
230 * @since 11 |
96 * @since 11 |
231 */ |
97 */ |
232 public abstract class HttpRequest { |
98 public abstract class HttpRequest { |
233 |
99 |
235 * Creates an HttpRequest. |
101 * Creates an HttpRequest. |
236 */ |
102 */ |
237 protected HttpRequest() {} |
103 protected HttpRequest() {} |
238 |
104 |
239 /** |
105 /** |
240 * A builder of {@linkplain HttpRequest HTTP Requests}. |
106 * A builder of {@linkplain HttpRequest HTTP requests}. |
241 * |
107 * |
242 * <p> Instances of {@code HttpRequest.Builder} are created by calling {@link |
108 * <p> Instances of {@code HttpRequest.Builder} are created by calling {@link |
243 * HttpRequest#newBuilder(URI)} or {@link HttpRequest#newBuilder()}. |
109 * HttpRequest#newBuilder(URI)} or {@link HttpRequest#newBuilder()}. |
244 * |
110 * |
245 * <p> Each of the setter methods in this class modifies the state of the |
111 * <p> Each of the setter methods in this class modifies the state of the |
246 * builder and returns <i>this</i> (ie. the same instance). The methods are |
112 * builder and returns <i>this</i> (ie. the same instance). The methods are |
247 * not synchronized and should not be called from multiple threads without |
113 * not synchronized and should not be called from multiple threads without |
248 * external synchronization. |
114 * external synchronization. The {@linkplain #build() build} method returns |
|
115 * a new {@code HttpRequest} each time it is invoked. Once built an {@code |
|
116 * HttpRequest} is immutable, and can be sent multiple times. |
249 * |
117 * |
250 * <p> Note, that not all request headers may be set by user code. Some are |
118 * <p> Note, that not all request headers may be set by user code. Some are |
251 * restricted for security reasons and others such as the headers relating |
119 * restricted for security reasons and others such as the headers relating |
252 * to authentication, redirection and cookie management are managed by |
120 * to authentication, redirection and cookie management may be managed by |
253 * specific APIs rather than through directly user set headers. |
121 * specific APIs rather than through directly user set headers. |
254 * |
|
255 * <p> The {@linkplain #build() build} method returns a new {@code |
|
256 * HttpRequest} each time it is invoked. |
|
257 * |
122 * |
258 * @since 11 |
123 * @since 11 |
259 */ |
124 */ |
260 public abstract static class Builder { |
125 public abstract static class Builder { |
261 |
126 |
569 + uri().hashCode() |
434 + uri().hashCode() |
570 + headers().hashCode(); |
435 + headers().hashCode(); |
571 } |
436 } |
572 |
437 |
573 /** |
438 /** |
574 * A Publisher which converts high level Java objects into flows of |
439 * A {@code BodyPublisher} converts high-level Java objects into a flow of |
575 * byte buffers suitable for sending as request bodies. |
440 * byte buffers suitable for sending as a request body. |
576 * |
441 * |
577 * <p> The {@code BodyPublisher} class implements {@link Flow.Publisher |
442 * <p> The {@code BodyPublisher} interface extends {@link Flow.Publisher |
578 * Flow.Publisher<ByteBuffer>} which means that a {@code BodyPublisher} |
443 * Flow.Publisher<ByteBuffer>}, which means that a {@code BodyPublisher} |
579 * acts as a publisher of {@linkplain ByteBuffer byte buffers}. |
444 * acts as a publisher of {@linkplain ByteBuffer byte buffers}. |
580 * |
445 * |
581 * <p> The HTTP client implementation subscribes to the publisher in order |
446 * <p> When sending a request that contains a body, the HTTP Client |
582 * to receive the flow of outgoing data buffers. The normal semantics of |
447 * subscribes to the request's {@code BodyPublisher} in order to receive the |
583 * {@link Flow.Subscriber} and {@link Flow.Publisher} are implemented by the |
448 * flow of outgoing request body data. The normal semantics of {@link |
584 * library and are expected from publisher implementations. Each outgoing |
449 * Flow.Subscriber} and {@link Flow.Publisher} are implemented by the HTTP |
585 * request results in one {@code Subscriber} subscribing to the {@code |
450 * Client and are expected from {@code BodyPublisher} implementations. Each |
586 * BodyPublisher} in order to provide the sequence of byte buffers |
451 * outgoing request results in one HTTP Client {@code Subscriber} |
587 * containing the request body. |
452 * subscribing to the {@code BodyPublisher} in order to provide the sequence |
588 * Instances of {@code ByteBuffer} published by the publisher must be |
453 * of byte buffers containing the request body. Instances of {@code |
589 * allocated by the publisher, and must not be accessed after being handed |
454 * ByteBuffer} published by the publisher must be allocated by the |
590 * over to the library. |
455 * publisher, and must not be accessed after being published to the HTTP |
591 * These subscriptions complete normally when the request is fully sent, |
456 * Client. These subscriptions complete normally when the request body is |
592 * and can be canceled or terminated early through error. If a request |
457 * fully sent, and can be canceled or terminated early through error. If a |
593 * needs to be resent for any reason, then a new subscription is created |
458 * request needs to be resent for any reason, then a new subscription is |
594 * which is expected to generate the same data as before. |
459 * created which is expected to generate the same data as before. |
595 * |
460 * |
596 * <p> A publisher that reports a {@linkplain #contentLength() content |
461 * <p> A {@code BodyPublisher} that reports a {@linkplain #contentLength() |
597 * length} of {@code 0} may not be subscribed to by the HTTP client |
462 * content length} of {@code 0} may not be subscribed to by the HTTP Client, |
598 * implementation, as it has effectively no data to publish. |
463 * as it has effectively no data to publish. |
599 */ |
464 */ |
600 public interface BodyPublisher extends Flow.Publisher<ByteBuffer> { |
465 public interface BodyPublisher extends Flow.Publisher<ByteBuffer> { |
601 |
466 |
602 /** |
467 /** |
603 * Returns a request body publisher whose body is retrieved from the |
468 * Returns a request body publisher whose body is retrieved from the |