Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.net.http/share/classes/java/net/http/HttpRequest.java
41159 views
1
/*
2
* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.net.http;
27
28
import java.io.FileNotFoundException;
29
import java.io.InputStream;
30
import java.net.URI;
31
import java.nio.ByteBuffer;
32
import java.nio.charset.Charset;
33
import java.nio.charset.StandardCharsets;
34
import java.nio.file.Files;
35
import java.nio.file.OpenOption;
36
import java.nio.file.Path;
37
import java.time.Duration;
38
import java.util.Iterator;
39
import java.util.Objects;
40
import java.util.Optional;
41
import java.util.concurrent.Flow;
42
import java.util.function.BiPredicate;
43
import java.util.function.Supplier;
44
45
import jdk.internal.net.http.HttpRequestBuilderImpl;
46
import jdk.internal.net.http.RequestPublishers;
47
48
import static java.nio.charset.StandardCharsets.UTF_8;
49
50
/**
51
* An HTTP request.
52
*
53
* <p> An {@code HttpRequest} instance is built through an {@code HttpRequest}
54
* {@linkplain HttpRequest.Builder builder}. An {@code HttpRequest} builder
55
* is obtained from one of the {@link HttpRequest#newBuilder(URI) newBuilder}
56
* methods. A request's {@link URI}, headers, and body can be set. Request
57
* bodies are provided through a {@link BodyPublisher BodyPublisher} supplied
58
* to one of the {@link Builder#POST(BodyPublisher) POST},
59
* {@link Builder#PUT(BodyPublisher) PUT} or
60
* {@link Builder#method(String,BodyPublisher) method} methods.
61
* Once all required parameters have been set in the builder, {@link
62
* Builder#build() build} will return the {@code HttpRequest}. Builders can be
63
* copied and modified many times in order to build multiple related requests
64
* that differ in some parameters.
65
*
66
* <p> The following is an example of a GET request that prints the response
67
* body as a String:
68
*
69
* <pre>{@code HttpClient client = HttpClient.newHttpClient();
70
* HttpRequest request = HttpRequest.newBuilder()
71
* .uri(URI.create("http://foo.com/"))
72
* .build();
73
* client.sendAsync(request, BodyHandlers.ofString())
74
* .thenApply(HttpResponse::body)
75
* .thenAccept(System.out::println)
76
* .join(); }</pre>
77
*
78
* <p>The class {@link BodyPublishers BodyPublishers} provides implementations
79
* of many common publishers. Alternatively, a custom {@code BodyPublisher}
80
* implementation can be used.
81
*
82
* @since 11
83
*/
84
public abstract class HttpRequest {
85
86
/**
87
* Creates an HttpRequest.
88
*/
89
protected HttpRequest() {}
90
91
/**
92
* A builder of {@linkplain HttpRequest HTTP requests}.
93
*
94
* <p> Instances of {@code HttpRequest.Builder} are created by calling
95
* {@link HttpRequest#newBuilder()}, {@link HttpRequest#newBuilder(URI)},
96
* or {@link HttpRequest#newBuilder(HttpRequest, BiPredicate)}.
97
*
98
* <p> The builder can be used to configure per-request state, such as: the
99
* request URI, the request method (default is GET unless explicitly set),
100
* specific request headers, etc. Each of the setter methods modifies the
101
* state of the builder and returns the same instance. The methods are not
102
* synchronized and should not be called from multiple threads without
103
* external synchronization. The {@link #build() build} method returns a new
104
* {@code HttpRequest} each time it is invoked. Once built an {@code
105
* HttpRequest} is immutable, and can be sent multiple times.
106
*
107
* <p> Note, that not all request headers may be set by user code. Some are
108
* restricted for security reasons and others such as the headers relating
109
* to authentication, redirection and cookie management may be managed by
110
* specific APIs rather than through directly user set headers.
111
*
112
* @since 11
113
*/
114
public interface Builder {
115
116
/**
117
* Sets this {@code HttpRequest}'s request {@code URI}.
118
*
119
* @param uri the request URI
120
* @return this builder
121
* @throws IllegalArgumentException if the {@code URI} scheme is not
122
* supported
123
*/
124
public Builder uri(URI uri);
125
126
/**
127
* Requests the server to acknowledge the request before sending the
128
* body. This is disabled by default. If enabled, the server is
129
* requested to send an error response or a {@code 100 Continue}
130
* response before the client sends the request body. This means the
131
* request publisher for the request will not be invoked until this
132
* interim response is received.
133
*
134
* @param enable {@code true} if Expect continue to be sent
135
* @return this builder
136
*/
137
public Builder expectContinue(boolean enable);
138
139
/**
140
* Sets the preferred {@link HttpClient.Version} for this request.
141
*
142
* <p> The corresponding {@link HttpResponse} should be checked for the
143
* version that was actually used. If the version is not set in a
144
* request, then the version requested will be that of the sending
145
* {@link HttpClient}.
146
*
147
* @param version the HTTP protocol version requested
148
* @return this builder
149
*/
150
public Builder version(HttpClient.Version version);
151
152
/**
153
* Adds the given name value pair to the set of headers for this request.
154
* The given value is added to the list of values for that name.
155
*
156
* @implNote An implementation may choose to restrict some header names
157
* or values, as the HTTP Client may determine their value itself.
158
* For example, "Content-Length", which will be determined by
159
* the request Publisher. In such a case, an implementation of
160
* {@code HttpRequest.Builder} may choose to throw an
161
* {@code IllegalArgumentException} if such a header is passed
162
* to the builder.
163
*
164
* @param name the header name
165
* @param value the header value
166
* @return this builder
167
* @throws IllegalArgumentException if the header name or value is not
168
* valid, see <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
169
* RFC 7230 section-3.2</a>, or the header name or value is restricted
170
* by the implementation.
171
*/
172
public Builder header(String name, String value);
173
174
/**
175
* Adds the given name value pairs to the set of headers for this
176
* request. The supplied {@code String} instances must alternate as
177
* header names and header values.
178
* To add several values to the same name then the same name must
179
* be supplied with each new value.
180
*
181
* @param headers the list of name value pairs
182
* @return this builder
183
* @throws IllegalArgumentException if there are an odd number of
184
* parameters, or if a header name or value is not valid, see
185
* <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
186
* RFC 7230 section-3.2</a>, or a header name or value is
187
* {@linkplain #header(String, String) restricted} by the
188
* implementation.
189
*/
190
public Builder headers(String... headers);
191
192
/**
193
* Sets a timeout for this request. If the response is not received
194
* within the specified timeout then an {@link HttpTimeoutException} is
195
* thrown from {@link HttpClient#send(java.net.http.HttpRequest,
196
* java.net.http.HttpResponse.BodyHandler) HttpClient::send} or
197
* {@link HttpClient#sendAsync(java.net.http.HttpRequest,
198
* java.net.http.HttpResponse.BodyHandler) HttpClient::sendAsync}
199
* completes exceptionally with an {@code HttpTimeoutException}. The effect
200
* of not setting a timeout is the same as setting an infinite Duration,
201
* i.e. block forever.
202
*
203
* @param duration the timeout duration
204
* @return this builder
205
* @throws IllegalArgumentException if the duration is non-positive
206
*/
207
public abstract Builder timeout(Duration duration);
208
209
/**
210
* Sets the given name value pair to the set of headers for this
211
* request. This overwrites any previously set values for name.
212
*
213
* @param name the header name
214
* @param value the header value
215
* @return this builder
216
* @throws IllegalArgumentException if the header name or value is not valid,
217
* see <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
218
* RFC 7230 section-3.2</a>, or the header name or value is
219
* {@linkplain #header(String, String) restricted} by the
220
* implementation.
221
*/
222
public Builder setHeader(String name, String value);
223
224
/**
225
* Sets the request method of this builder to GET.
226
* This is the default.
227
*
228
* @return this builder
229
*/
230
public Builder GET();
231
232
/**
233
* Sets the request method of this builder to POST and sets its
234
* request body publisher to the given value.
235
*
236
* @param bodyPublisher the body publisher
237
*
238
* @return this builder
239
*/
240
public Builder POST(BodyPublisher bodyPublisher);
241
242
/**
243
* Sets the request method of this builder to PUT and sets its
244
* request body publisher to the given value.
245
*
246
* @param bodyPublisher the body publisher
247
*
248
* @return this builder
249
*/
250
public Builder PUT(BodyPublisher bodyPublisher);
251
252
/**
253
* Sets the request method of this builder to DELETE.
254
*
255
* @return this builder
256
*/
257
public Builder DELETE();
258
259
/**
260
* Sets the request method and request body of this builder to the
261
* given values.
262
*
263
* @apiNote The {@link BodyPublishers#noBody() noBody} request
264
* body publisher can be used where no request body is required or
265
* appropriate. Whether a method is restricted, or not, is
266
* implementation specific. For example, some implementations may choose
267
* to restrict the {@code CONNECT} method.
268
*
269
* @param method the method to use
270
* @param bodyPublisher the body publisher
271
* @return this builder
272
* @throws IllegalArgumentException if the method name is not
273
* valid, see <a href="https://tools.ietf.org/html/rfc7230#section-3.1.1">
274
* RFC 7230 section-3.1.1</a>, or the method is restricted by the
275
* implementation.
276
*/
277
public Builder method(String method, BodyPublisher bodyPublisher);
278
279
/**
280
* Builds and returns an {@link HttpRequest}.
281
*
282
* @return a new {@code HttpRequest}
283
* @throws IllegalStateException if a URI has not been set
284
*/
285
public HttpRequest build();
286
287
/**
288
* Returns an exact duplicate copy of this {@code Builder} based on
289
* current state. The new builder can then be modified independently of
290
* this builder.
291
*
292
* @return an exact copy of this builder
293
*/
294
public Builder copy();
295
}
296
297
/**
298
* Creates an {@code HttpRequest} builder with the given URI.
299
*
300
* @param uri the request URI
301
* @return a new request builder
302
* @throws IllegalArgumentException if the URI scheme is not supported.
303
*/
304
public static HttpRequest.Builder newBuilder(URI uri) {
305
return new HttpRequestBuilderImpl(uri);
306
}
307
308
/**
309
* Creates a {@code Builder} whose initial state is copied from an existing
310
* {@code HttpRequest}.
311
*
312
* <p> This builder can be used to build an {@code HttpRequest}, equivalent
313
* to the original, while allowing amendment of the request state prior to
314
* construction - for example, adding additional headers.
315
*
316
* <p> The {@code filter} is applied to each header name value pair as they
317
* are copied from the given request. When completed, only headers that
318
* satisfy the condition as laid out by the {@code filter} will be present
319
* in the {@code Builder} returned from this method.
320
*
321
* @apiNote
322
* The following scenarios demonstrate typical use-cases of the filter.
323
* Given an {@code HttpRequest} <em>request</em>:
324
* <br><br>
325
* <ul>
326
* <li> Retain all headers:
327
* <pre>{@code HttpRequest.newBuilder(request, (n, v) -> true)}</pre>
328
*
329
* <li> Remove all headers:
330
* <pre>{@code HttpRequest.newBuilder(request, (n, v) -> false)}</pre>
331
*
332
* <li> Remove a particular header (e.g. Foo-Bar):
333
* <pre>{@code HttpRequest.newBuilder(request, (name, value) -> !name.equalsIgnoreCase("Foo-Bar"))}</pre>
334
* </ul>
335
*
336
* @param request the original request
337
* @param filter a header filter
338
* @return a new request builder
339
* @throws IllegalArgumentException if a new builder cannot be seeded from
340
* the given request (for instance, if the request contains illegal
341
* parameters)
342
* @since 16
343
*/
344
public static Builder newBuilder(HttpRequest request, BiPredicate<String, String> filter) {
345
Objects.requireNonNull(request);
346
Objects.requireNonNull(filter);
347
348
final HttpRequest.Builder builder = HttpRequest.newBuilder();
349
builder.uri(request.uri());
350
builder.expectContinue(request.expectContinue());
351
352
// Filter unwanted headers
353
HttpHeaders headers = HttpHeaders.of(request.headers().map(), filter);
354
headers.map().forEach((name, values) ->
355
values.forEach(value -> builder.header(name, value)));
356
357
request.version().ifPresent(builder::version);
358
request.timeout().ifPresent(builder::timeout);
359
var method = request.method();
360
request.bodyPublisher().ifPresentOrElse(
361
// if body is present, set it
362
bodyPublisher -> builder.method(method, bodyPublisher),
363
// otherwise, the body is absent, special case for GET/DELETE,
364
// or else use empty body
365
() -> {
366
switch (method) {
367
case "GET" -> builder.GET();
368
case "DELETE" -> builder.DELETE();
369
default -> builder.method(method, HttpRequest.BodyPublishers.noBody());
370
}
371
}
372
);
373
return builder;
374
}
375
376
/**
377
* Creates an {@code HttpRequest} builder.
378
*
379
* @return a new request builder
380
*/
381
public static HttpRequest.Builder newBuilder() {
382
return new HttpRequestBuilderImpl();
383
}
384
385
/**
386
* Returns an {@code Optional} containing the {@link BodyPublisher} set on
387
* this request. If no {@code BodyPublisher} was set in the requests's
388
* builder, then the {@code Optional} is empty.
389
*
390
* @return an {@code Optional} containing this request's {@code BodyPublisher}
391
*/
392
public abstract Optional<BodyPublisher> bodyPublisher();
393
394
/**
395
* Returns the request method for this request. If not set explicitly,
396
* the default method for any request is "GET".
397
*
398
* @return this request's method
399
*/
400
public abstract String method();
401
402
/**
403
* Returns an {@code Optional} containing this request's timeout duration.
404
* If the timeout duration was not set in the request's builder, then the
405
* {@code Optional} is empty.
406
*
407
* @return an {@code Optional} containing this request's timeout duration
408
*/
409
public abstract Optional<Duration> timeout();
410
411
/**
412
* Returns this request's {@linkplain HttpRequest.Builder#expectContinue(boolean)
413
* expect continue} setting.
414
*
415
* @return this request's expect continue setting
416
*/
417
public abstract boolean expectContinue();
418
419
/**
420
* Returns this request's {@code URI}.
421
*
422
* @return this request's URI
423
*/
424
public abstract URI uri();
425
426
/**
427
* Returns an {@code Optional} containing the HTTP protocol version that
428
* will be requested for this {@code HttpRequest}. If the version was not
429
* set in the request's builder, then the {@code Optional} is empty.
430
* In that case, the version requested will be that of the sending
431
* {@link HttpClient}. The corresponding {@link HttpResponse} should be
432
* queried to determine the version that was actually used.
433
*
434
* @return HTTP protocol version
435
*/
436
public abstract Optional<HttpClient.Version> version();
437
438
/**
439
* The (user-accessible) request headers that this request was (or will be)
440
* sent with.
441
*
442
* @return this request's HttpHeaders
443
*/
444
public abstract HttpHeaders headers();
445
446
/**
447
* Tests this HTTP request instance for equality with the given object.
448
*
449
* <p> If the given object is not an {@code HttpRequest} then this
450
* method returns {@code false}. Two HTTP requests are equal if their URI,
451
* method, and headers fields are all equal.
452
*
453
* <p> This method satisfies the general contract of the {@link
454
* Object#equals(Object) Object.equals} method.
455
*
456
* @param obj the object to which this object is to be compared
457
* @return {@code true} if, and only if, the given object is an {@code
458
* HttpRequest} that is equal to this HTTP request
459
*/
460
@Override
461
public final boolean equals(Object obj) {
462
if (! (obj instanceof HttpRequest))
463
return false;
464
HttpRequest that = (HttpRequest)obj;
465
if (!that.method().equals(this.method()))
466
return false;
467
if (!that.uri().equals(this.uri()))
468
return false;
469
if (!that.headers().equals(this.headers()))
470
return false;
471
return true;
472
}
473
474
/**
475
* Computes a hash code for this HTTP request instance.
476
*
477
* <p> The hash code is based upon the HTTP request's URI, method, and
478
* header components, and satisfies the general contract of the
479
* {@link Object#hashCode Object.hashCode} method.
480
*
481
* @return the hash-code value for this HTTP request
482
*/
483
public final int hashCode() {
484
return method().hashCode()
485
+ uri().hashCode()
486
+ headers().hashCode();
487
}
488
489
/**
490
* A {@code BodyPublisher} converts high-level Java objects into a flow of
491
* byte buffers suitable for sending as a request body. The class
492
* {@link BodyPublishers BodyPublishers} provides implementations of many
493
* common publishers.
494
*
495
* <p> The {@code BodyPublisher} interface extends {@link Flow.Publisher
496
* Flow.Publisher&lt;ByteBuffer&gt;}, which means that a {@code BodyPublisher}
497
* acts as a publisher of {@linkplain ByteBuffer byte buffers}.
498
*
499
* <p> When sending a request that contains a body, the HTTP Client
500
* subscribes to the request's {@code BodyPublisher} in order to receive the
501
* flow of outgoing request body data. The normal semantics of {@link
502
* Flow.Subscriber} and {@link Flow.Publisher} are implemented by the HTTP
503
* Client and are expected from {@code BodyPublisher} implementations. Each
504
* outgoing request results in one HTTP Client {@code Subscriber}
505
* subscribing to the {@code BodyPublisher} in order to provide the sequence
506
* of byte buffers containing the request body. Instances of {@code
507
* ByteBuffer} published by the publisher must be allocated by the
508
* publisher, and must not be accessed after being published to the HTTP
509
* Client. These subscriptions complete normally when the request body is
510
* fully sent, and can be canceled or terminated early through error. If a
511
* request needs to be resent for any reason, then a new subscription is
512
* created which is expected to generate the same data as before.
513
*
514
* <p> A {@code BodyPublisher} that reports a {@linkplain #contentLength()
515
* content length} of {@code 0} may not be subscribed to by the HTTP Client,
516
* as it has effectively no data to publish.
517
*
518
* @see BodyPublishers
519
* @since 11
520
*/
521
public interface BodyPublisher extends Flow.Publisher<ByteBuffer> {
522
523
/**
524
* Returns the content length for this request body. May be zero
525
* if no request body being sent, greater than zero for a fixed
526
* length content, or less than zero for an unknown content length.
527
*
528
* <p> This method may be invoked before the publisher is subscribed to.
529
* This method may be invoked more than once by the HTTP client
530
* implementation, and MUST return the same constant value each time.
531
*
532
* @return the content length for this request body, if known
533
*/
534
long contentLength();
535
}
536
537
/**
538
* Implementations of {@link BodyPublisher BodyPublisher} that implement
539
* various useful publishers, such as publishing the request body from a
540
* String, or from a file.
541
*
542
* <p> The following are examples of using the predefined body publishers to
543
* convert common high-level Java objects into a flow of data suitable for
544
* sending as a request body:
545
*
546
* <pre>{@code // Request body from a String
547
* HttpRequest request = HttpRequest.newBuilder()
548
* .uri(URI.create("https://foo.com/"))
549
* .header("Content-Type", "text/plain; charset=UTF-8")
550
* .POST(BodyPublishers.ofString("some body text"))
551
* .build();
552
*
553
* // Request body from a File
554
* HttpRequest request = HttpRequest.newBuilder()
555
* .uri(URI.create("https://foo.com/"))
556
* .header("Content-Type", "application/json")
557
* .POST(BodyPublishers.ofFile(Paths.get("file.json")))
558
* .build();
559
*
560
* // Request body from a byte array
561
* HttpRequest request = HttpRequest.newBuilder()
562
* .uri(URI.create("https://foo.com/"))
563
* .POST(BodyPublishers.ofByteArray(new byte[] { ... }))
564
* .build(); }</pre>
565
*
566
* @since 11
567
*/
568
public static class BodyPublishers {
569
570
private BodyPublishers() { }
571
572
/**
573
* Returns a request body publisher whose body is retrieved from the
574
* given {@code Flow.Publisher}. The returned request body publisher
575
* has an unknown content length.
576
*
577
* @apiNote This method can be used as an adapter between {@code
578
* BodyPublisher} and {@code Flow.Publisher}, where the amount of
579
* request body that the publisher will publish is unknown.
580
*
581
* @param publisher the publisher responsible for publishing the body
582
* @return a BodyPublisher
583
*/
584
public static BodyPublisher
585
fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher) {
586
return new RequestPublishers.PublisherAdapter(publisher, -1L);
587
}
588
589
/**
590
* Returns a request body publisher whose body is retrieved from the
591
* given {@code Flow.Publisher}. The returned request body publisher
592
* has the given content length.
593
*
594
* <p> The given {@code contentLength} is a positive number, that
595
* represents the exact amount of bytes the {@code publisher} must
596
* publish.
597
*
598
* @apiNote This method can be used as an adapter between {@code
599
* BodyPublisher} and {@code Flow.Publisher}, where the amount of
600
* request body that the publisher will publish is known.
601
*
602
* @param publisher the publisher responsible for publishing the body
603
* @param contentLength a positive number representing the exact
604
* amount of bytes the publisher will publish
605
* @throws IllegalArgumentException if the content length is
606
* non-positive
607
* @return a BodyPublisher
608
*/
609
public static BodyPublisher
610
fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher,
611
long contentLength) {
612
if (contentLength < 1)
613
throw new IllegalArgumentException("non-positive contentLength: "
614
+ contentLength);
615
return new RequestPublishers.PublisherAdapter(publisher, contentLength);
616
}
617
618
/**
619
* Returns a request body publisher whose body is the given {@code
620
* String}, converted using the {@link StandardCharsets#UTF_8 UTF_8}
621
* character set.
622
*
623
* @param body the String containing the body
624
* @return a BodyPublisher
625
*/
626
public static BodyPublisher ofString(String body) {
627
return ofString(body, UTF_8);
628
}
629
630
/**
631
* Returns a request body publisher whose body is the given {@code
632
* String}, converted using the given character set.
633
*
634
* @param s the String containing the body
635
* @param charset the character set to convert the string to bytes
636
* @return a BodyPublisher
637
*/
638
public static BodyPublisher ofString(String s, Charset charset) {
639
return new RequestPublishers.StringPublisher(s, charset);
640
}
641
642
/**
643
* A request body publisher that reads its data from an {@link
644
* InputStream}. A {@link Supplier} of {@code InputStream} is used in
645
* case the request needs to be repeated, as the content is not buffered.
646
* The {@code Supplier} may return {@code null} on subsequent attempts,
647
* in which case the request fails.
648
*
649
* @param streamSupplier a Supplier of open InputStreams
650
* @return a BodyPublisher
651
*/
652
// TODO (spec): specify that the stream will be closed
653
public static BodyPublisher ofInputStream(Supplier<? extends InputStream> streamSupplier) {
654
return new RequestPublishers.InputStreamPublisher(streamSupplier);
655
}
656
657
/**
658
* Returns a request body publisher whose body is the given byte array.
659
*
660
* @param buf the byte array containing the body
661
* @return a BodyPublisher
662
*/
663
public static BodyPublisher ofByteArray(byte[] buf) {
664
return new RequestPublishers.ByteArrayPublisher(buf);
665
}
666
667
/**
668
* Returns a request body publisher whose body is the content of the
669
* given byte array of {@code length} bytes starting from the specified
670
* {@code offset}.
671
*
672
* @param buf the byte array containing the body
673
* @param offset the offset of the first byte
674
* @param length the number of bytes to use
675
* @return a BodyPublisher
676
* @throws IndexOutOfBoundsException if the sub-range is defined to be
677
* out of bounds
678
*/
679
public static BodyPublisher ofByteArray(byte[] buf, int offset, int length) {
680
Objects.checkFromIndexSize(offset, length, buf.length);
681
return new RequestPublishers.ByteArrayPublisher(buf, offset, length);
682
}
683
684
/**
685
* A request body publisher that takes data from the contents of a File.
686
*
687
* <p> Security manager permission checks are performed in this factory
688
* method, when the {@code BodyPublisher} is created. Care must be taken
689
* that the {@code BodyPublisher} is not shared with untrusted code.
690
*
691
* @param path the path to the file containing the body
692
* @return a BodyPublisher
693
* @throws java.io.FileNotFoundException if the path is not found
694
* @throws SecurityException if
695
* {@linkplain Files#newInputStream(Path, OpenOption...)
696
* opening the file for reading} is denied:
697
* in the case of the system-default file system provider,
698
* and a security manager is installed,
699
* {@link SecurityManager#checkRead(String) checkRead}
700
* is invoked to check read access to the given file
701
*/
702
public static BodyPublisher ofFile(Path path) throws FileNotFoundException {
703
Objects.requireNonNull(path);
704
return RequestPublishers.FilePublisher.create(path);
705
}
706
707
/**
708
* A request body publisher that takes data from an {@code Iterable}
709
* of byte arrays. An {@link Iterable} is provided which supplies
710
* {@link Iterator} instances. Each attempt to send the request results
711
* in one invocation of the {@code Iterable}.
712
*
713
* @param iter an Iterable of byte arrays
714
* @return a BodyPublisher
715
*/
716
public static BodyPublisher ofByteArrays(Iterable<byte[]> iter) {
717
return new RequestPublishers.IterablePublisher(iter);
718
}
719
720
/**
721
* A request body publisher which sends no request body.
722
*
723
* @return a BodyPublisher which completes immediately and sends
724
* no request body.
725
*/
726
public static BodyPublisher noBody() {
727
return new RequestPublishers.EmptyPublisher();
728
}
729
730
/**
731
* Returns a {@code BodyPublisher} that publishes a request
732
* body consisting of the concatenation of the request bodies
733
* published by a sequence of publishers.
734
*
735
* <p> If the sequence is empty an {@linkplain #noBody() empty} publisher
736
* is returned. Otherwise, if the sequence contains a single element,
737
* that publisher is returned. Otherwise a <em>concatenation publisher</em>
738
* is returned.
739
*
740
* <p> The request body published by a <em>concatenation publisher</em>
741
* is logically equivalent to the request body that would have
742
* been published by concatenating all the bytes of each publisher
743
* in sequence.
744
*
745
* <p> Each publisher is lazily subscribed to in turn,
746
* until all the body bytes are published, an error occurs, or the
747
* concatenation publisher's subscription is cancelled.
748
* The concatenation publisher may be subscribed to more than once,
749
* which in turn may result in the publishers in the sequence being
750
* subscribed to more than once.
751
*
752
* <p> The concatenation publisher has a known content
753
* length only if all publishers in the sequence have a known content
754
* length. The {@link BodyPublisher#contentLength() contentLength}
755
* reported by the concatenation publisher is computed as follows:
756
* <ul>
757
* <li> If any of the publishers reports an <em>{@linkplain
758
* BodyPublisher#contentLength() unknown}</em> content length,
759
* or if the sum of the known content lengths would exceed
760
* {@link Long#MAX_VALUE}, the resulting
761
* content length is <em>unknown</em>.</li>
762
* <li> Otherwise, the resulting content length is the sum of the
763
* known content lengths, a number between
764
* {@code 0} and {@link Long#MAX_VALUE}, inclusive.</li>
765
* </ul>
766
*
767
* @implNote If the concatenation publisher's subscription is
768
* {@linkplain Flow.Subscription#cancel() cancelled}, or an error occurs
769
* while publishing the bytes, not all publishers in the sequence may
770
* be subscribed to.
771
*
772
* @param publishers a sequence of publishers.
773
* @return An aggregate publisher that publishes a request body
774
* logically equivalent to the concatenation of all bytes published
775
* by each publisher in the sequence.
776
*
777
* @since 16
778
*/
779
public static BodyPublisher concat(BodyPublisher... publishers) {
780
return RequestPublishers.concat(Objects.requireNonNull(publishers));
781
}
782
}
783
}
784
785