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.List;
 40 import java.util.Map;
 41 import java.util.Objects;
 42 import java.util.Optional;
 43 import java.util.concurrent.Flow;
 44 import java.util.function.BiFunction;
 45 import java.util.function.Supplier;
 46 import jdk.internal.net.http.HttpRequestBuilderImpl;
 47 import jdk.internal.net.http.RequestPublishers;
 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 {@link
 95      * HttpRequest#newBuilder(URI)} or {@link HttpRequest#newBuilder()}.
 96      *
 97      * <p> The builder can be used to configure per-request state, such as: the
 98      * request URI, the request method (default is GET unless explicitly set),
 99      * specific request headers, etc. Each of the setter methods modifies the
100      * state of the builder and returns the same instance. The methods are not
101      * synchronized and should not be called from multiple threads without
102      * external synchronization. The {@link #build() build} method returns a new
103      * {@code HttpRequest} each time it is invoked. Once built an {@code
104      * HttpRequest} is immutable, and can be sent multiple times.
105      *
106      * <p> Note, that not all request headers may be set by user code. Some are
107      * restricted for security reasons and others such as the headers relating
108      * to authentication, redirection and cookie management may be managed by
109      * specific APIs rather than through directly user set headers.
110      *
111      * @since 11
112      */
113     public interface Builder {
114 
115         /**
116          * Sets this {@code HttpRequest}'s request {@code URI}.
117          *
118          * @param uri the request URI
119          * @return this builder
120          * @throws IllegalArgumentException if the {@code URI} scheme is not
121          *         supported
122          */
123         public Builder uri(URI uri);
124 
125         /**
126          * Requests the server to acknowledge the request before sending the
127          * body. This is disabled by default. If enabled, the server is
128          * requested to send an error response or a {@code 100 Continue}
129          * response before the client sends the request body. This means the
130          * request publisher for the request will not be invoked until this
131          * interim response is received.
132          *
133          * @param enable {@code true} if Expect continue to be sent
134          * @return this builder
135          */
136         public Builder expectContinue(boolean enable);
137 
138         /**
139          * Sets the preferred {@link HttpClient.Version} for this request.
140          *
141          * <p> The corresponding {@link HttpResponse} should be checked for the
142          * version that was actually used. If the version is not set in a
143          * request, then the version requested will be that of the sending
144          * {@link HttpClient}.
145          *
146          * @param version the HTTP protocol version requested
147          * @return this builder
148          */
149         public Builder version(HttpClient.Version version);
150 
151         /**
152          * Adds the given name value pair to the set of headers for this request.
153          * The given value is added to the list of values for that name.
154          *
155          * @implNote An implementation may choose to restrict some header names
156          *           or values, as the HTTP Client may determine their value itself.
157          *           For example, "Content-Length", which will be determined by
158          *           the request Publisher. In such a case, an implementation of
159          *           {@code HttpRequest.Builder} may choose to throw an
160          *           {@code IllegalArgumentException} if such a header is passed
161          *           to the builder.
162          *
163          * @param name the header name
164          * @param value the header value
165          * @return this builder
166          * @throws IllegalArgumentException if the header name or value is not
167          *         valid, see <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
168          *         RFC 7230 section-3.2</a>, or the header name or value is restricted
169          *         by the implementation.
170          */
171         public Builder header(String name, String value);
172 
173         /**
174          * Adds the given name value pairs to the set of headers for this
175          * request. The supplied {@code String} instances must alternate as
176          * header names and header values.
177          * To add several values to the same name then the same name must
178          * be supplied with each new value.
179          *
180          * @param headers the list of name value pairs
181          * @return this builder
182          * @throws IllegalArgumentException if there are an odd number of
183          *         parameters, or if a header name or value is not valid, see
184          *         <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
185          *         RFC 7230 section-3.2</a>, or a header name or value is
186          *         {@linkplain #header(String, String) restricted} by the
187          *         implementation.
188          */
189         public Builder headers(String... headers);
190 
191         /**
192          * Sets a timeout for this request. If the response is not received
193          * within the specified timeout then an {@link HttpTimeoutException} is
194          * thrown from {@link HttpClient#send(java.net.http.HttpRequest,
195          * java.net.http.HttpResponse.BodyHandler) HttpClient::send} or
196          * {@link HttpClient#sendAsync(java.net.http.HttpRequest,
197          * java.net.http.HttpResponse.BodyHandler) HttpClient::sendAsync}
198          * completes exceptionally with an {@code HttpTimeoutException}. The effect
199          * of not setting a timeout is the same as setting an infinite Duration,
200          * i.e. block forever.
201          *
202          * @param duration the timeout duration
203          * @return this builder
204          * @throws IllegalArgumentException if the duration is non-positive
205          */
206         public abstract Builder timeout(Duration duration);
207 
208         /**
209          * Sets the given name value pair to the set of headers for this
210          * request. This overwrites any previously set values for name.
211          *
212          * @param name the header name
213          * @param value the header value
214          * @return this builder
215          * @throws IllegalArgumentException if the header name or value is not valid,
216          *         see <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
217          *         RFC 7230 section-3.2</a>, or the header name or value is
218          *         {@linkplain #header(String, String) restricted} by the
219          *         implementation.
220          */
221         public Builder setHeader(String name, String value);
222 
223         /**
224          * Sets the request method of this builder to GET.
225          * This is the default.
226          *
227          * @return this builder
228          */
229         public Builder GET();
230 
231         /**
232          * Sets the request method of this builder to POST and sets its
233          * request body publisher to the given value.
234          *
235          * @param bodyPublisher the body publisher
236          *
237          * @return this builder
238          */
239         public Builder POST(BodyPublisher bodyPublisher);
240 
241         /**
242          * Sets the request method of this builder to PUT and sets its
243          * request body publisher to the given value.
244          *
245          * @param bodyPublisher the body publisher
246          *
247          * @return this builder
248          */
249         public Builder PUT(BodyPublisher bodyPublisher);
250 
251         /**
252          * Sets the request method of this builder to DELETE.
253          *
254          * @return this builder
255          */
256         public Builder DELETE();
257 
258         /**
259          * Sets the request method and request body of this builder to the
260          * given values.
261          *
262          * @apiNote The {@link BodyPublishers#noBody() noBody} request
263          * body publisher can be used where no request body is required or
264          * appropriate. Whether a method is restricted, or not, is
265          * implementation specific. For example, some implementations may choose
266          * to restrict the {@code CONNECT} method.
267          *
268          * @param method the method to use
269          * @param bodyPublisher the body publisher
270          * @return this builder
271          * @throws IllegalArgumentException if the method name is not
272          *         valid, see <a href="https://tools.ietf.org/html/rfc7230#section-3.1.1">
273          *         RFC 7230 section-3.1.1</a>, or the method is restricted by the
274          *         implementation.
275          */
276         public Builder method(String method, BodyPublisher bodyPublisher);
277 
278         /**
279          * Builds and returns an {@link HttpRequest}.
280          *
281          * @return a new {@code HttpRequest}
282          * @throws IllegalStateException if a URI has not been set
283          */
284         public HttpRequest build();
285 
286         /**
287          * Returns an exact duplicate copy of this {@code Builder} based on
288          * current state. The new builder can then be modified independently of
289          * this builder.
290          *
291          * @return an exact copy of this builder
292          */
293         public Builder copy();
294     }
295 
296     /**
297      * Creates an {@code HttpRequest} builder with the given URI.
298      *
299      * @param uri the request URI
300      * @return a new request builder
301      * @throws IllegalArgumentException if the URI scheme is not supported.
302      */
303     public static HttpRequest.Builder newBuilder(URI uri) {
304         return new HttpRequestBuilderImpl(uri);
305     }
306 
307     /**
308      * Creates an {@code HttpRequest} builder.
309      *
310      * @return a new request builder
311      */
312     public static HttpRequest.Builder newBuilder() {
313         return new HttpRequestBuilderImpl();
314     }
315 
316     /**
317      * Returns an {@code Optional} containing the {@link BodyPublisher} set on
318      * this request. If no {@code BodyPublisher} was set in the requests's
319      * builder, then the {@code Optional} is empty.
320      *
321      * @return an {@code Optional} containing this request's {@code BodyPublisher}
322      */
323     public abstract Optional<BodyPublisher> bodyPublisher();
324 
325     /**
326      * Returns the request method for this request. If not set explicitly,
327      * the default method for any request is "GET".
328      *
329      * @return this request's method
330      */
331     public abstract String method();
332 
333     /**
334      * Returns an {@code Optional} containing this request's timeout duration.
335      * If the timeout duration was not set in the request's builder, then the
336      * {@code Optional} is empty.
337      *
338      * @return an {@code Optional} containing this request's timeout duration
339      */
340     public abstract Optional<Duration> timeout();
341 
342     /**
343      * Returns this request's {@linkplain HttpRequest.Builder#expectContinue(boolean)
344      * expect continue} setting.
345      *
346      * @return this request's expect continue setting
347      */
348     public abstract boolean expectContinue();
349 
350     /**
351      * Returns this request's {@code URI}.
352      *
353      * @return this request's URI
354      */
355     public abstract URI uri();
356 
357     /**
358      * Returns an {@code Optional} containing the HTTP protocol version that
359      * will be requested for this {@code HttpRequest}. If the version was not
360      * set in the request's builder, then the {@code Optional} is empty.
361      * In that case, the version requested will be that of the sending
362      * {@link HttpClient}. The corresponding {@link HttpResponse} should be
363      * queried to determine the version that was actually used.
364      *
365      * @return HTTP protocol version
366      */
367     public abstract Optional<HttpClient.Version> version();
368 
369     /**
370      * The (user-accessible) request headers that this request was (or will be)
371      * sent with.
372      *
373      * @return this request's HttpHeaders
374      */
375     public abstract HttpHeaders headers();
376 
377     /**
378      * Tests this HTTP request instance for equality with the given object.
379      *
380      * <p> If the given object is not an {@code HttpRequest} then this
381      * method returns {@code false}. Two HTTP requests are equal if their URI,
382      * method, and headers fields are all equal.
383      *
384      * <p> This method satisfies the general contract of the {@link
385      * Object#equals(Object) Object.equals} method.
386      *
387      * @param obj the object to which this object is to be compared
388      * @return {@code true} if, and only if, the given object is an {@code
389      *         HttpRequest} that is equal to this HTTP request
390      */
391     @Override
392     public final boolean equals(Object obj) {
393        if (! (obj instanceof HttpRequest))
394            return false;
395        HttpRequest that = (HttpRequest)obj;
396        if (!that.method().equals(this.method()))
397            return false;
398        if (!that.uri().equals(this.uri()))
399            return false;
400        if (!that.headers().equals(this.headers()))
401            return false;
402        return true;
403     }
404 
405     /**
406      * Computes a hash code for this HTTP request instance.
407      *
408      * <p> The hash code is based upon the HTTP request's URI, method, and
409      * header components, and satisfies the general contract of the
410      * {@link Object#hashCode Object.hashCode} method.
411      *
412      * @return the hash-code value for this HTTP request
413      */
414     public final int hashCode() {
415         return method().hashCode()
416                 + uri().hashCode()
417                 + headers().hashCode();
418     }
419 
420     /**
421      * A {@code BodyPublisher} converts high-level Java objects into a flow of
422      * byte buffers suitable for sending as a request body.  The class
423      * {@link BodyPublishers BodyPublishers} provides implementations of many
424      * common publishers.
425      *
426      * <p> The {@code BodyPublisher} interface extends {@link Flow.Publisher
427      * Flow.Publisher&lt;ByteBuffer&gt;}, which means that a {@code BodyPublisher}
428      * acts as a publisher of {@linkplain ByteBuffer byte buffers}.
429      *
430      * <p> When sending a request that contains a body, the HTTP Client
431      * subscribes to the request's {@code BodyPublisher} in order to receive the
432      * flow of outgoing request body data. The normal semantics of {@link
433      * Flow.Subscriber} and {@link Flow.Publisher} are implemented by the HTTP
434      * Client and are expected from {@code BodyPublisher} implementations. Each
435      * outgoing request results in one HTTP Client {@code Subscriber}
436      * subscribing to the {@code BodyPublisher} in order to provide the sequence
437      * of byte buffers containing the request body. Instances of {@code
438      * ByteBuffer} published by the publisher must be allocated by the
439      * publisher, and must not be accessed after being published to the HTTP
440      * Client. These subscriptions complete normally when the request body is
441      * fully sent, and can be canceled or terminated early through error. If a
442      * request needs to be resent for any reason, then a new subscription is
443      * created which is expected to generate the same data as before.
444      *
445      * <p> A {@code BodyPublisher} that reports a {@linkplain #contentLength()
446      * content length} of {@code 0} may not be subscribed to by the HTTP Client,
447      * as it has effectively no data to publish.
448      *
449      * @see BodyPublishers
450      * @since 11
451      */
452     public interface BodyPublisher extends Flow.Publisher<ByteBuffer> {
453 
454         /**
455          * Returns the content length for this request body. May be zero
456          * if no request body being sent, greater than zero for a fixed
457          * length content, or less than zero for an unknown content length.
458          *
459          * <p> This method may be invoked before the publisher is subscribed to.
460          * This method may be invoked more than once by the HTTP client
461          * implementation, and MUST return the same constant value each time.
462          *
463          * @return the content length for this request body, if known
464          */
465         long contentLength();
466     }
467 
468     /**
469      * Implementations of {@link BodyPublisher BodyPublisher} that implement
470      * various useful publishers, such as publishing the request body from a
471      * String, or from a file.
472      *
473      * <p> The following are examples of using the predefined body publishers to
474      * convert common high-level Java objects into a flow of data suitable for
475      * sending as a request body:
476      *
477      *  <pre>{@code    // Request body from a String
478      *   HttpRequest request = HttpRequest.newBuilder()
479      *        .uri(URI.create("https://foo.com/"))
480      *        .header("Content-Type", "text/plain; charset=UTF-8")
481      *        .POST(BodyPublishers.ofString("some body text"))
482      *        .build();
483      *
484      *   // Request body from a File
485      *   HttpRequest request = HttpRequest.newBuilder()
486      *        .uri(URI.create("https://foo.com/"))
487      *        .header("Content-Type", "application/json")
488      *        .POST(BodyPublishers.ofFile(Paths.get("file.json")))
489      *        .build();
490      *
491      *   // Request body from a byte array
492      *   HttpRequest request = HttpRequest.newBuilder()
493      *        .uri(URI.create("https://foo.com/"))
494      *        .POST(BodyPublishers.ofByteArray(new byte[] { ... }))
495      *        .build(); }</pre>
496      *
497      * @since 11
498      */
499     public static class BodyPublishers {
500 
501         private BodyPublishers() { }
502 
503         /**
504          * Returns a request body publisher whose body is retrieved from the
505          * given {@code Flow.Publisher}. The returned request body publisher
506          * has an unknown content length.
507          *
508          * @apiNote This method can be used as an adapter between {@code
509          * BodyPublisher} and {@code Flow.Publisher}, where the amount of
510          * request body that the publisher will publish is unknown.
511          *
512          * @param publisher the publisher responsible for publishing the body
513          * @return a BodyPublisher
514          */
515         public static BodyPublisher
516         fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher) {
517             return new RequestPublishers.PublisherAdapter(publisher, -1L);
518         }
519 
520         /**
521          * Returns a request body publisher whose body is retrieved from the
522          * given {@code Flow.Publisher}. The returned request body publisher
523          * has the given content length.
524          *
525          * <p> The given {@code contentLength} is a positive number, that
526          * represents the exact amount of bytes the {@code publisher} must
527          * publish.
528          *
529          * @apiNote This method can be used as an adapter between {@code
530          * BodyPublisher} and {@code Flow.Publisher}, where the amount of
531          * request body that the publisher will publish is known.
532          *
533          * @param publisher the publisher responsible for publishing the body
534          * @param contentLength a positive number representing the exact
535          *                      amount of bytes the publisher will publish
536          * @throws IllegalArgumentException if the content length is
537          *                                  non-positive
538          * @return a BodyPublisher
539          */
540         public static BodyPublisher
541         fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher,
542                       long contentLength) {
543             if (contentLength < 1)
544                 throw new IllegalArgumentException("non-positive contentLength: "
545                         + contentLength);
546             return new RequestPublishers.PublisherAdapter(publisher, contentLength);
547         }
548 
549         /**
550          * Returns a request body publisher whose body is the given {@code
551          * String}, converted using the {@link StandardCharsets#UTF_8 UTF_8}
552          * character set.
553          *
554          * @param body the String containing the body
555          * @return a BodyPublisher
556          */
557         public static BodyPublisher ofString(String body) {
558             return ofString(body, UTF_8);
559         }
560 
561         /**
562          * Returns a request body publisher whose body is the given {@code
563          * String}, converted using the given character set.
564          *
565          * @param s the String containing the body
566          * @param charset the character set to convert the string to bytes
567          * @return a BodyPublisher
568          */
569         public static BodyPublisher ofString(String s, Charset charset) {
570             return new RequestPublishers.StringPublisher(s, charset);
571         }
572 
573         /**
574          * A request body publisher that reads its data from an {@link
575          * InputStream}. A {@link Supplier} of {@code InputStream} is used in
576          * case the request needs to be repeated, as the content is not buffered.
577          * The {@code Supplier} may return {@code null} on subsequent attempts,
578          * in which case the request fails.
579          *
580          * @param streamSupplier a Supplier of open InputStreams
581          * @return a BodyPublisher
582          */
583         // TODO (spec): specify that the stream will be closed
584         public static BodyPublisher ofInputStream(Supplier<? extends InputStream> streamSupplier) {
585             return new RequestPublishers.InputStreamPublisher(streamSupplier);
586         }
587 
588         /**
589          * Returns a request body publisher whose body is the given byte array.
590          *
591          * @param buf the byte array containing the body
592          * @return a BodyPublisher
593          */
594         public static BodyPublisher ofByteArray(byte[] buf) {
595             return new RequestPublishers.ByteArrayPublisher(buf);
596         }
597 
598         /**
599          * Returns a request body publisher whose body is the content of the
600          * given byte array of {@code length} bytes starting from the specified
601          * {@code offset}.
602          *
603          * @param buf the byte array containing the body
604          * @param offset the offset of the first byte
605          * @param length the number of bytes to use
606          * @return a BodyPublisher
607          * @throws IndexOutOfBoundsException if the sub-range is defined to be
608          *                                   out of bounds
609          */
610         public static BodyPublisher ofByteArray(byte[] buf, int offset, int length) {
611             Objects.checkFromIndexSize(offset, length, buf.length);
612             return new RequestPublishers.ByteArrayPublisher(buf, offset, length);
613         }
614 
615         /**
616          * A request body publisher that takes data from the contents of a File.
617          *
618          * <p> Security manager permission checks are performed in this factory
619          * method, when the {@code BodyPublisher} is created. Care must be taken
620          * that the {@code BodyPublisher} is not shared with untrusted code.
621          *
622          * @param  path the path to the file containing the body
623          * @return a BodyPublisher
624          * @throws java.io.FileNotFoundException if the path is not found
625          * @throws SecurityException if
626          *         {@linkplain Files#newInputStream(Path, OpenOption...)
627          *         opening the file for reading} is denied:
628          *         in the case of the system-default file system provider,
629          *         and a security manager is installed,
630          *         {@link SecurityManager#checkRead(String) checkRead}
631          *         is invoked to check read access to the given file
632          */
633         public static BodyPublisher ofFile(Path path) throws FileNotFoundException {
634             Objects.requireNonNull(path);
635             return RequestPublishers.FilePublisher.create(path);
636         }
637 
638         /**
639          * A request body publisher that takes data from an {@code Iterable}
640          * of byte arrays. An {@link Iterable} is provided which supplies
641          * {@link Iterator} instances. Each attempt to send the request results
642          * in one invocation of the {@code Iterable}.
643          *
644          * @param iter an Iterable of byte arrays
645          * @return a BodyPublisher
646          */
647         public static BodyPublisher ofByteArrays(Iterable<byte[]> iter) {
648             return new RequestPublishers.IterablePublisher(iter);
649         }
650 
651         /**
652          * A request body publisher which sends no request body.
653          *
654          * @return a BodyPublisher which completes immediately and sends
655          *         no request body.
656          */
657         public static BodyPublisher noBody() {
658             return new RequestPublishers.EmptyPublisher();
659         }
660 
661         // -- Minimal piece of low-level machinery
662 
663         /**
664          * A request body publisher which publishes items emitted by each of the
665          * given request body publishers, one after the other, without
666          * interleaving.
667          *
668          * // TODO: tighten spec, subscribe to each publisher in turn, drain,
669          * // to onComplete, next... Any error encountered is propagated and
670          * // no further activity, etc ...
671          * // The content-length of the returned publisher will be that of the
672          * // accumulated publisher lengths, unless any is unknown in which case
673          * // the returned publisher's content-length is unknown.
674          *
675          * @param publishers an array of request body publishers
676          * @return a BodyPublisher composed of the given publishers
677          * @throws IllegalArgumentException if publishers array is less than 2
678          */
679         public static BodyPublisher concat(BodyPublisher... publishers) {
680             Objects.requireNonNull(publishers);
681             if (publishers.length < 2)
682                 throw new IllegalArgumentException("error");
683 
684             return null; // TODO implement
685         }
686 
687         // -- The following are three alternatives to support multipart common syntax
688 
689         /**
690          * A multipart part!  Alternative #1 requires a carrier tuple (Uck!)
691          *
692          * @headers the, possibly empty, part's headers  << headers are optional
693          * @publisher the non-null part's publisher
694          */
695         public static record Part(HttpHeaders headers, BodyPublisher publisher) { }
696 
697         /**
698          * A multipart request body publisher...
699          *
700          * Publishes each of the given parts, one after another, in order. Each
701          * part is separated by the given boundary.
702          *
703          * // TODO: tighten spec, content-length?, etc
704          *
705          * TODO: supports the multipart common syntax, see https://tools.ietf.org/html/rfc2046#section-5.1.1
706          *
707          * One can embed multipart inside multipart - verify
708          *
709          * @param boundary a non-null boundary
710          * @param parts an non-null array of multipart parts
711          * @throws IllegalArgumentException if boundary not less than 70 chars ...
712          *         if parts does not contain at least one element ...
713          * @return a multipart BodyPublisher
714          */
715         // Alternative #1
716         public static BodyPublisher ofMultipart(String boundary, Part... parts) {
717             return null; // TODO implement
718         }
719 
720         // Alternative #2
721         public static BodyPublisher ofMultipart2(String boundary,
722                                                  List<Map.Entry<HttpHeaders,BodyPublisher>> parts) {
723             return null; // TODO implement
724         }
725 
726         // Alternative #3
727         public static BodyPublisher ofMultipart3(String boundary,
728                                                  BodyPublisher... parts) {  // this is ambiguous(ish) OR maybe not, default ascii/text?
729             return null; // TODO implement
730         }
731 
732         public static BodyPublisher multipartPart(HttpHeaders headers,  // what a name!
733                                                   BodyPublisher publisher) {
734             return concat(ofString(headers.toString()), publisher);  // Argh! header to string representation
735         }
736     }
737 }