Class HttpRequest.BodyPublishers
- Enclosing class:
HttpRequest
BodyPublisher that implement
various useful publishers, such as publishing the request body from a
String, or from a file.
The following are examples of using the predefined body publishers to convert common high-level Java objects into a flow of data suitable for sending as a request body:
// Request body from a String
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.header("Content-Type", "text/plain; charset=UTF-8")
.POST(BodyPublishers.ofString("some body text"))
.build();
// Request body from a File
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
// Request body from a byte array
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.POST(BodyPublishers.ofByteArray(new byte[] { ... }))
.build();
- Since:
- 11
-
Method Summary
Modifier and TypeMethodDescriptionstatic HttpRequest.BodyPublisherconcat(HttpRequest.BodyPublisher... publishers) Returns aBodyPublisherthat publishes a request body consisting of the concatenation of the request bodies published by a sequence of publishers.static HttpRequest.BodyPublisherfromPublisher(Flow.Publisher<? extends ByteBuffer> publisher) Returns a request body publisher whose body is retrieved from the givenFlow.Publisher.static HttpRequest.BodyPublisherfromPublisher(Flow.Publisher<? extends ByteBuffer> publisher, long contentLength) Returns a request body publisher whose body is retrieved from the givenFlow.Publisher.static HttpRequest.BodyPublishernoBody()A request body publisher which sends no request body.static HttpRequest.BodyPublisherofByteArray(byte[] buf) Returns a request body publisher whose body is the given byte array.static HttpRequest.BodyPublisherofByteArray(byte[] buf, int offset, int length) Returns a request body publisher whose body is the content of the given byte array oflengthbytes starting from the specifiedoffset.static HttpRequest.BodyPublisherofByteArrays(Iterable<byte[]> iter) A request body publisher that takes data from anIterableof byte arrays.static HttpRequest.BodyPublisherA request body publisher that takes data from the contents of a File.static HttpRequest.BodyPublisherofFileChannel(FileChannel channel, long offset, long length) Returns a request body publisher whose body is thelengthcontent bytes read from the provided filechannelstarting from the specifiedoffset.static HttpRequest.BodyPublisherofInputStream(Supplier<? extends InputStream> streamSupplier) A request body publisher that reads its data from anInputStream.static HttpRequest.BodyPublisherReturns a request body publisher whose body is the givenString, converted using theUTF_8character set.static HttpRequest.BodyPublisherReturns a request body publisher whose body is the givenString, converted using the given character set.Methods declared in class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitModifier and TypeMethodDescriptionprotected Objectclone()Answers a new instance of the same class as the receiver, whose slots have been filled in with the values in the slots of the receiver.booleanCompares the argument to the receiver, and answers true if they represent the same object using a class specific comparison.protected voidfinalize()Deprecated, for removal: This API element is subject to removal in a future version.May cause performance issues, deadlocks and hangs.getClass()Answers the unique instance of java.lang.Class which represents the class of the receiver.inthashCode()Answers an integer hash code for the receiver.final voidnotify()Causes one thread which iswaiting on the receiver to be made ready to run.final voidCauses all threads which arewaiting on the receiver to be made ready to run.toString()Answers a string containing a concise, human-readable description of the receiver.final voidwait()Causes the thread which sent this message to be made not ready to run pending some change in the receiver (as indicated bynotifyornotifyAll).final voidwait(long time) Causes the thread which sent this message to be made not ready to run either pending some change in the receiver (as indicated bynotifyornotifyAll) or the expiration of the timeout.final voidwait(long time, int frac) Causes the thread which sent this message to be made not ready to run either pending some change in the receiver (as indicated bynotifyornotifyAll) or the expiration of the timeout.
-
Method Details
-
fromPublisher
public static HttpRequest.BodyPublisher fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher) Returns a request body publisher whose body is retrieved from the givenFlow.Publisher. The returned request body publisher has an unknown content length.- API Note:
- This method can be used as an adapter between
BodyPublisherandFlow.Publisher, where the amount of request body that the publisher will publish is unknown. - Parameters:
publisher- the publisher responsible for publishing the body- Returns:
- a BodyPublisher
-
fromPublisher
public static HttpRequest.BodyPublisher fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher, long contentLength) Returns a request body publisher whose body is retrieved from the givenFlow.Publisher. The returned request body publisher has the given content length.The given
contentLengthis a positive number, that represents the exact amount of bytes thepublishermust publish.- API Note:
- This method can be used as an adapter between
BodyPublisherandFlow.Publisher, where the amount of request body that the publisher will publish is known. - Parameters:
publisher- the publisher responsible for publishing the bodycontentLength- a positive number representing the exact amount of bytes the publisher will publish- Returns:
- a BodyPublisher
- Throws:
IllegalArgumentException- if the content length is non-positive
-
ofString
Returns a request body publisher whose body is the givenString, converted using theUTF_8character set.- Parameters:
body- the String containing the body- Returns:
- a BodyPublisher
-
ofString
Returns a request body publisher whose body is the givenString, converted using the given character set.- Parameters:
s- the String containing the bodycharset- the character set to convert the string to bytes- Returns:
- a BodyPublisher
-
ofInputStream
public static HttpRequest.BodyPublisher ofInputStream(Supplier<? extends InputStream> streamSupplier) A request body publisher that reads its data from anInputStream. ASupplierofInputStreamis used in case the request needs to be repeated, as the content is not buffered. TheSuppliermay returnnullon subsequent attempts, in which case the request fails.- Parameters:
streamSupplier- a Supplier of open InputStreams- Returns:
- a BodyPublisher
-
ofByteArray
Returns a request body publisher whose body is the given byte array.- Parameters:
buf- the byte array containing the body- Returns:
- a BodyPublisher
-
ofByteArray
Returns a request body publisher whose body is the content of the given byte array oflengthbytes starting from the specifiedoffset.- Parameters:
buf- the byte array containing the bodyoffset- the offset of the first bytelength- the number of bytes to use- Returns:
- a BodyPublisher
- Throws:
IndexOutOfBoundsException- if the sub-range is defined to be out of bounds
-
ofFile
A request body publisher that takes data from the contents of a File.- Parameters:
path- the path to the file containing the body- Returns:
- a BodyPublisher
- Throws:
FileNotFoundException- if the path is not found
-
ofFileChannel
public static HttpRequest.BodyPublisher ofFileChannel(FileChannel channel, long offset, long length) throws IOException Returns a request body publisher whose body is thelengthcontent bytes read from the provided filechannelstarting from the specifiedoffset.This method and the returned
BodyPublisherdo not modify thechannel's position, and do not close thechannel. The caller is expected to close thechannelwhen no longer needed.- API Note:
- This method can be used to either publish just a region of a file as
the request body or to publish different regions of a file
concurrently. A typical usage would be to publish different regions
of a file by creating a single instance of
FileChanneland then send multiple concurrentHttpRequests, each of which uses a newofFileChannel BodyPublishercreated from the same channel with a different, typically non-overlapping, range of bytes specified by offset and length. - Parameters:
channel- a file channeloffset- the offset of the first bytelength- the number of bytes to read from the file channel- Returns:
- a request body publisher whose body is the
lengthcontent bytes read from the provided filechannelstarting from the specifiedoffset - Throws:
IndexOutOfBoundsException- if the specified byte range is found to be out of bounds compared with the size of the file referred by the channelIOException- if the channel's size cannot be determined or thechannelis closed- Since:
- 26
-
ofByteArrays
-
noBody
A request body publisher which sends no request body.- Returns:
- a BodyPublisher which completes immediately and sends no request body.
-
concat
Returns aBodyPublisherthat publishes a request body consisting of the concatenation of the request bodies published by a sequence of publishers.If the sequence is empty an empty publisher is returned. Otherwise, if the sequence contains a single element, that publisher is returned. Otherwise a concatenation publisher is returned.
The request body published by a concatenation publisher is logically equivalent to the request body that would have been published by concatenating all the bytes of each publisher in sequence.
Each publisher is lazily subscribed to in turn, until all the body bytes are published, an error occurs, or the concatenation publisher's subscription is cancelled. The concatenation publisher may be subscribed to more than once, which in turn may result in the publishers in the sequence being subscribed to more than once.
The concatenation publisher has a known content length only if all publishers in the sequence have a known content length. The
contentLengthreported by the concatenation publisher is computed as follows:- If any of the publishers reports an unknown content length,
or if the sum of the known content lengths would exceed
Long.MAX_VALUE, the resulting content length is unknown. - Otherwise, the resulting content length is the sum of the
known content lengths, a number between
0andLong.MAX_VALUE, inclusive.
- Implementation Note:
- If the concatenation publisher's subscription is cancelled, or an error occurs while publishing the bytes, not all publishers in the sequence may be subscribed to.
- Parameters:
publishers- a sequence of publishers.- Returns:
- An aggregate publisher that publishes a request body logically equivalent to the concatenation of all bytes published by each publisher in the sequence.
- Since:
- 16
- If any of the publishers reports an unknown content length,
or if the sum of the known content lengths would exceed
-