Top Description Inners Constructors Methods
java.net.http

public abstract Class HttpRequest

extends Object
Class Inheritance
Known Direct Subclasses
jdk.internal.net.http.HttpRequestImpl, jdk.internal.net.http.ImmutableHttpRequest
Imports
java.io.FileNotFoundException, .InputStream, java.net.URI, java.nio.ByteBuffer, java.nio.charset.Charset, .StandardCharsets, java.nio.file.Files, .OpenOption, .Path, java.time.Duration, java.util.Iterator, .Objects, .Optional, java.util.concurrent.Flow, java.util.function.BiPredicate, .Supplier, jdk.internal.net.http.HttpRequestBuilderImpl, .RequestPublishers

An HTTP request.

An HttpRequest instance is built through an HttpRequest builder. An HttpRequest builder is obtained from one of the newBuilder methods. A request's URI, headers, and body can be set. Request bodies are provided through a BodyPublisher supplied to one of the POST, PUT or method methods. Once all required parameters have been set in the builder, build will return the HttpRequest. Builders can be copied and modified many times in order to build multiple related requests that differ in some parameters.

The following is an example of a GET request that prints the response body as a String:

HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://foo.com/")) .build(); client.sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join();
HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://foo.com/"))
      .build();

client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

The class BodyPublishers provides implementations of many common publishers. Alternatively, a custom BodyPublisher implementation can be used.

Since
11

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
HttpRequest.BodyPublisher

A BodyPublisher converts high-level Java objects into a flow of byte buffers suitable for sending as a request body.

public static class
HttpRequest.BodyPublishers

Implementations of BodyPublisher that implement various useful publishers, such as publishing the request body from a String, or from a file.

public static interface

Constructor Summary

AccessConstructor and Description
protected
HttpRequest()

Creates an HttpRequest.

Method Summary

Modifier and TypeMethod and Description
public abstract Optional<HttpRequest.BodyPublisher>

Returns:

an Optional containing this request's BodyPublisher
bodyPublisher
()

Returns an Optional containing the BodyPublisher set on this request.

public final boolean

Returns:

true if, and only if, the given object is an HttpRequest that is equal to this HTTP request
equals
(Object
the object to which this object is to be compared
obj
)

Overrides java.lang.Object.equals.

Tests this HTTP request instance for equality with the given object.

public abstract boolean

Returns:

this request's expect continue setting
expectContinue
()

Returns this request's expect continue setting.

public final int

Returns:

the hash-code value for this HTTP request
hashCode
()

Overrides java.lang.Object.hashCode.

Computes a hash code for this HTTP request instance.

public abstract HttpHeaders

Returns:

this request's HttpHeaders
headers
()

The (user-accessible) request headers that this request was (or will be) sent with.

public abstract String

Returns:

this request's method
method
()

Returns the request method for this request.

public static HttpRequest.Builder

Returns:

a new request builder
newBuilder
(URI
the request URI
uri
)

Creates an HttpRequest builder with the given URI.

public static HttpRequest.Builder

Returns:

a new request builder
newBuilder
(HttpRequest
the original request
request
,
BiPredicate<String, String>
a header filter
filter
)

Creates a Builder whose initial state is copied from an existing HttpRequest.

public static HttpRequest.Builder

Returns:

a new request builder
newBuilder
()

Creates an HttpRequest builder.

public abstract Optional<Duration>

Returns:

an Optional containing this request's timeout duration
timeout
()

Returns an Optional containing this request's timeout duration.

public abstract URI

Returns:

this request's URI
uri
()

Returns this request's URI.

public abstract Optional<HttpClient.Version>

Returns:

HTTP protocol version
version
()

Returns an Optional containing the HTTP protocol version that will be requested for this HttpRequest.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAlltoStringwaitwaitwait

Constructor Detail

HttpRequestback to summary
protected HttpRequest()

Creates an HttpRequest.

Method Detail

bodyPublisherback to summary
public abstract Optional<HttpRequest.BodyPublisher> bodyPublisher()

Returns an Optional containing the BodyPublisher set on this request. If no BodyPublisher was set in the requests's builder, then the Optional is empty.

Returns:Optional<HttpRequest.BodyPublisher>

an Optional containing this request's BodyPublisher

equalsback to summary
public final boolean equals(Object obj)

Overrides java.lang.Object.equals.

Tests this HTTP request instance for equality with the given object.

If the given object is not an HttpRequest then this method returns false. Two HTTP requests are equal if their URI, method, and headers fields are all equal.

This method satisfies the general contract of the Object.equals method.

Parameters
obj:Object

the object to which this object is to be compared

Returns:boolean

true if, and only if, the given object is an HttpRequest that is equal to this HTTP request

Annotations
@Override
expectContinueback to summary
public abstract boolean expectContinue()

Returns this request's expect continue setting.

Returns:boolean

this request's expect continue setting

hashCodeback to summary
public final int hashCode()

Overrides java.lang.Object.hashCode.

Computes a hash code for this HTTP request instance.

The hash code is based upon the HTTP request's URI, method, and header components, and satisfies the general contract of the Object.hashCode method.

Returns:int

the hash-code value for this HTTP request

headersback to summary
public abstract HttpHeaders headers()

The (user-accessible) request headers that this request was (or will be) sent with.

Returns:HttpHeaders

this request's HttpHeaders

methodback to summary
public abstract String method()

Returns the request method for this request. If not set explicitly, the default method for any request is "GET".

Returns:String

this request's method

newBuilderback to summary
public static HttpRequest.Builder newBuilder(URI uri)

Creates an HttpRequest builder with the given URI.

Parameters
uri:URI

the request URI

Returns:HttpRequest.Builder

a new request builder

Exceptions
IllegalArgumentException:
if the URI scheme is not supported.
newBuilderback to summary
public static HttpRequest.Builder newBuilder(HttpRequest request, BiPredicate<String, String> filter)

Creates a Builder whose initial state is copied from an existing HttpRequest.

This builder can be used to build an HttpRequest, equivalent to the original, while allowing amendment of the request state prior to construction - for example, adding additional headers.

The filter is applied to each header name value pair as they are copied from the given request. When completed, only headers that satisfy the condition as laid out by the filter will be present in the Builder returned from this method.

API Note

The following scenarios demonstrate typical use-cases of the filter. Given an HttpRequest request:

  • Retain all headers:
    HttpRequest.newBuilder(request, (n, v) -> true)
    HttpRequest.newBuilder(request, (n, v) -> true)
    
  • Remove all headers:
    HttpRequest.newBuilder(request, (n, v) -> false)
    HttpRequest.newBuilder(request, (n, v) -> false)
    
  • Remove a particular header (e.g. Foo-Bar):
    HttpRequest.newBuilder(request, (name, value) -> !name.equalsIgnoreCase("Foo-Bar"))
    HttpRequest.newBuilder(request, (name, value) -> !name.equalsIgnoreCase("Foo-Bar"))
    
Parameters
request:HttpRequest

the original request

filter:BiPredicate<String, String>

a header filter

Returns:HttpRequest.Builder

a new request builder

Exceptions
IllegalArgumentException:
if a new builder cannot be seeded from the given request (for instance, if the request contains illegal parameters)
Since
16
newBuilderback to summary
public static HttpRequest.Builder newBuilder()

Creates an HttpRequest builder.

Returns:HttpRequest.Builder

a new request builder

timeoutback to summary
public abstract Optional<Duration> timeout()

Returns an Optional containing this request's timeout duration. If the timeout duration was not set in the request's builder, then the Optional is empty.

Returns:Optional<Duration>

an Optional containing this request's timeout duration

uriback to summary
public abstract URI uri()

Returns this request's URI.

Returns:URI

this request's URI

versionback to summary
public abstract Optional<HttpClient.Version> version()

Returns an Optional containing the HTTP protocol version that will be requested for this HttpRequest. If the version was not set in the request's builder, then the Optional is empty. In that case, the version requested will be that of the sending HttpClient. The corresponding HttpResponse should be queried to determine the version that was actually used.

Returns:Optional<HttpClient.Version>

HTTP protocol version

java.net.http back to summary

public Interface HttpRequest.BodyPublisher

extends Flow.Publisher<ByteBuffer>
Known Direct Implementers
jdk.internal.net.http.RequestPublishers.ByteArrayPublisher, jdk.internal.net.http.RequestPublishers.IterablePublisher, jdk.internal.net.http.RequestPublishers.EmptyPublisher, jdk.internal.net.http.RequestPublishers.FilePublisher, jdk.internal.net.http.RequestPublishers.InputStreamPublisher, jdk.internal.net.http.RequestPublishers.PublisherAdapter, jdk.internal.net.http.RequestPublishers.AggregatePublisher

A BodyPublisher converts high-level Java objects into a flow of byte buffers suitable for sending as a request body. The class BodyPublishers provides implementations of many common publishers.

The BodyPublisher interface extends Flow.Publisher<ByteBuffer>, which means that a BodyPublisher acts as a publisher of byte buffers.

When sending a request that contains a body, the HTTP Client subscribes to the request's BodyPublisher in order to receive the flow of outgoing request body data. The normal semantics of Flow.Subscriber and Flow.Publisher are implemented by the HTTP Client and are expected from BodyPublisher implementations. Each outgoing request results in one HTTP Client Subscriber subscribing to the BodyPublisher in order to provide the sequence of byte buffers containing the request body. Instances of ByteBuffer published by the publisher must be allocated by the publisher, and must not be accessed after being published to the HTTP Client. These subscriptions complete normally when the request body is fully sent, and can be canceled or terminated early through error. If a request needs to be resent for any reason, then a new subscription is created which is expected to generate the same data as before.

A BodyPublisher that reports a content length of 0 may not be subscribed to by the HTTP Client, as it has effectively no data to publish.

Since
11
See Also
BodyPublishers

Method Summary

Modifier and TypeMethod and Description
public long

Returns:

the content length for this request body, if known
contentLength
()

Returns the content length for this request body.

Inherited from java.util.concurrent.Flow.Publisher:
subscribe

Method Detail

contentLengthback to summary
public long contentLength()

Returns the content length for this request body. May be zero if no request body being sent, greater than zero for a fixed length content, or less than zero for an unknown content length.

This method may be invoked before the publisher is subscribed to. This method may be invoked more than once by the HTTP client implementation, and MUST return the same constant value each time.

Returns:long

the content length for this request body, if known

java.net.http back to summary

public Class HttpRequest.BodyPublishers

extends Object
Class Inheritance

Implementations of 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 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 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();
// Request body from a byte array
HttpRequest request = HttpRequest.newBuilder()
     .uri(URI.create("https://foo.com/"))
     .POST(BodyPublishers.ofByteArray(new byte[] { ... }))
     .build();
Since
11

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static HttpRequest.BodyPublisher

Returns:

An aggregate publisher that publishes a request body logically equivalent to the concatenation of all bytes published by each publisher in the sequence.
concat
(HttpRequest.BodyPublisher...
a sequence of publishers.
publishers
)

Returns a BodyPublisher that publishes a request body consisting of the concatenation of the request bodies published by a sequence of publishers.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
fromPublisher
(Flow.Publisher<? extends ByteBuffer>
the publisher responsible for publishing the body
publisher
)

Returns a request body publisher whose body is retrieved from the given Flow.Publisher.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
fromPublisher
(Flow.Publisher<? extends ByteBuffer>
the publisher responsible for publishing the body
publisher
,
long
a positive number representing the exact amount of bytes the publisher will publish
contentLength
)

Returns a request body publisher whose body is retrieved from the given Flow.Publisher.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher which completes immediately and sends no request body.
noBody
()

A request body publisher which sends no request body.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofByteArray
(byte[]
the byte array containing the body
buf
)

Returns a request body publisher whose body is the given byte array.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofByteArray
(byte[]
the byte array containing the body
buf
,
int
the offset of the first byte
offset
,
int
the number of bytes to use
length
)

Returns a request body publisher whose body is the content of the given byte array of length bytes starting from the specified offset.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofByteArrays
(Iterable<byte[]>
an Iterable of byte arrays
iter
)

A request body publisher that takes data from an Iterable of byte arrays.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofFile
(Path
the path to the file containing the body
path
)

A request body publisher that takes data from the contents of a File.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofInputStream
(Supplier<? extends InputStream>
a Supplier of open InputStreams
streamSupplier
)

A request body publisher that reads its data from an InputStream.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofString
(String
the String containing the body
body
)

Returns a request body publisher whose body is the given String, converted using the UTF_8 character set.

public static HttpRequest.BodyPublisher

Returns:

a BodyPublisher
ofString
(String
the String containing the body
s
,
Charset
the character set to convert the string to bytes
charset
)

Returns a request body publisher whose body is the given String, converted using the given character set.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

BodyPublishersback to summary
private BodyPublishers()

Method Detail

concatback to summary
public static HttpRequest.BodyPublisher concat(HttpRequest.BodyPublisher... publishers)

Returns a BodyPublisher that 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 contentLength reported 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 0 and Long#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:HttpRequest.BodyPublisher[]

a sequence of publishers.

Returns:HttpRequest.BodyPublisher

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
fromPublisherback to summary
public static HttpRequest.BodyPublisher fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher)

Returns a request body publisher whose body is retrieved from the given Flow.Publisher. The returned request body publisher has an unknown content length.

API Note

This method can be used as an adapter between BodyPublisher and Flow.Publisher, where the amount of request body that the publisher will publish is unknown.

Parameters
publisher:Flow.Publisher<? extends ByteBuffer>

the publisher responsible for publishing the body

Returns:HttpRequest.BodyPublisher

a BodyPublisher

fromPublisherback to summary
public static HttpRequest.BodyPublisher fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher, long contentLength)

Returns a request body publisher whose body is retrieved from the given Flow.Publisher. The returned request body publisher has the given content length.

The given contentLength is a positive number, that represents the exact amount of bytes the publisher must publish.

API Note

This method can be used as an adapter between BodyPublisher and Flow.Publisher, where the amount of request body that the publisher will publish is known.

Parameters
publisher:Flow.Publisher<? extends ByteBuffer>

the publisher responsible for publishing the body

contentLength:long

a positive number representing the exact amount of bytes the publisher will publish

Returns:HttpRequest.BodyPublisher

a BodyPublisher

Exceptions
IllegalArgumentException:
if the content length is non-positive
noBodyback to summary
public static HttpRequest.BodyPublisher noBody()

A request body publisher which sends no request body.

Returns:HttpRequest.BodyPublisher

a BodyPublisher which completes immediately and sends no request body.

ofByteArrayback to summary
public static HttpRequest.BodyPublisher ofByteArray(byte[] buf)

Returns a request body publisher whose body is the given byte array.

Parameters
buf:byte[]

the byte array containing the body

Returns:HttpRequest.BodyPublisher

a BodyPublisher

ofByteArrayback to summary
public static HttpRequest.BodyPublisher ofByteArray(byte[] buf, int offset, int length)

Returns a request body publisher whose body is the content of the given byte array of length bytes starting from the specified offset.

Parameters
buf:byte[]

the byte array containing the body

offset:int

the offset of the first byte

length:int

the number of bytes to use

Returns:HttpRequest.BodyPublisher

a BodyPublisher

Exceptions
IndexOutOfBoundsException:
if the sub-range is defined to be out of bounds
ofByteArraysback to summary
public static HttpRequest.BodyPublisher ofByteArrays(Iterable<byte[]> iter)

A request body publisher that takes data from an Iterable of byte arrays. An Iterable is provided which supplies Iterator instances. Each attempt to send the request results in one invocation of the Iterable.

Parameters
iter:Iterable<byte[]>

an Iterable of byte arrays

Returns:HttpRequest.BodyPublisher

a BodyPublisher

ofFileback to summary
public static HttpRequest.BodyPublisher ofFile(Path path) throws FileNotFoundException

A request body publisher that takes data from the contents of a File.

Security manager permission checks are performed in this factory method, when the BodyPublisher is created. Care must be taken that the BodyPublisher is not shared with untrusted code.

Parameters
path:Path

the path to the file containing the body

Returns:HttpRequest.BodyPublisher

a BodyPublisher

Exceptions
FileNotFoundException:
if the path is not found
SecurityException:
if opening the file for reading is denied: in the case of the system-default file system provider, and a security manager is installed, checkRead is invoked to check read access to the given file
ofInputStreamback to summary
public static HttpRequest.BodyPublisher ofInputStream(Supplier<? extends InputStream> streamSupplier)

A request body publisher that reads its data from an InputStream. A Supplier of InputStream is used in case the request needs to be repeated, as the content is not buffered. The Supplier may return null on subsequent attempts, in which case the request fails.

Parameters
streamSupplier:Supplier<? extends InputStream>

a Supplier of open InputStreams

Returns:HttpRequest.BodyPublisher

a BodyPublisher

ofStringback to summary
public static HttpRequest.BodyPublisher ofString(String body)

Returns a request body publisher whose body is the given String, converted using the UTF_8 character set.

Parameters
body:String

the String containing the body

Returns:HttpRequest.BodyPublisher

a BodyPublisher

ofStringback to summary
public static HttpRequest.BodyPublisher ofString(String s, Charset charset)

Returns a request body publisher whose body is the given String, converted using the given character set.

Parameters
s:String

the String containing the body

charset:Charset

the character set to convert the string to bytes

Returns:HttpRequest.BodyPublisher

a BodyPublisher

java.net.http back to summary

public Interface HttpRequest.Builder

Known Direct Implementers
jdk.internal.net.http.HttpRequestBuilderImpl

A builder of HTTP requests.

Instances of HttpRequest.Builder are created by calling HttpRequest#newBuilder(), HttpRequest#newBuilder(URI), or HttpRequest#newBuilder(HttpRequest, BiPredicate).

The builder can be used to configure per-request state, such as: the request URI, the request method (default is GET unless explicitly set), specific request headers, etc. Each of the setter methods modifies the state of the builder and returns the same instance. The methods are not synchronized and should not be called from multiple threads without external synchronization. The build method returns a new HttpRequest each time it is invoked. Once built an HttpRequest is immutable, and can be sent multiple times.

Note, that not all request headers may be set by user code. Some are restricted for security reasons and others such as the headers relating to authentication, redirection and cookie management may be managed by specific APIs rather than through directly user set headers.

Since
11

Method Summary

Modifier and TypeMethod and Description
public HttpRequest

Returns:

a new HttpRequest
build
()

Builds and returns an HttpRequest.

public HttpRequest.Builder

Returns:

an exact copy of this builder
copy
()

Returns an exact duplicate copy of this Builder based on current state.

public HttpRequest.Builder

Returns:

this builder
DELETE
()

Sets the request method of this builder to DELETE.

public HttpRequest.Builder

Returns:

this builder
expectContinue
(boolean
true if Expect continue to be sent
enable
)

Requests the server to acknowledge the request before sending the body.

public HttpRequest.Builder

Returns:

this builder
GET
()

Sets the request method of this builder to GET.

public default HttpRequest.Builder

Returns:

this builder
HEAD
()

Sets the request method of this builder to HEAD.

public HttpRequest.Builder

Returns:

this builder
header
(String
the header name
name
,
String
the header value
value
)

Adds the given name value pair to the set of headers for this request.

public HttpRequest.Builder

Returns:

this builder
headers
(String...
the list of name value pairs
headers
)

Adds the given name value pairs to the set of headers for this request.

public HttpRequest.Builder

Returns:

this builder
method
(String
the method to use
method
,
HttpRequest.BodyPublisher
the body publisher
bodyPublisher
)

Sets the request method and request body of this builder to the given values.

public HttpRequest.Builder

Returns:

this builder
POST
(HttpRequest.BodyPublisher
the body publisher
bodyPublisher
)

Sets the request method of this builder to POST and sets its request body publisher to the given value.

public HttpRequest.Builder

Returns:

this builder
PUT
(HttpRequest.BodyPublisher
the body publisher
bodyPublisher
)

Sets the request method of this builder to PUT and sets its request body publisher to the given value.

public HttpRequest.Builder

Returns:

this builder
setHeader
(String
the header name
name
,
String
the header value
value
)

Sets the given name value pair to the set of headers for this request.

public HttpRequest.Builder

Returns:

this builder
timeout
(Duration
the timeout duration
duration
)

Sets a timeout for this request.

public HttpRequest.Builder

Returns:

this builder
uri
(URI
the request URI
uri
)

Sets this HttpRequest's request URI.

public HttpRequest.Builder

Returns:

this builder
version
(HttpClient.Version
the HTTP protocol version requested
version
)

Sets the preferred HttpClient.Version for this request.

Method Detail

buildback to summary
public HttpRequest build()

Builds and returns an HttpRequest.

Implementation Specification

This method returns a new HttpRequest each time it is invoked. Once built, the HttpRequest is immutable and can be sent multiple times.

Returns:HttpRequest

a new HttpRequest

Exceptions
IllegalStateException:
if a URI has not been set
copyback to summary
public HttpRequest.Builder copy()

Returns an exact duplicate copy of this Builder based on current state. The new builder can then be modified independently of this builder.

Returns:HttpRequest.Builder

an exact copy of this builder

DELETEback to summary
public HttpRequest.Builder DELETE()

Sets the request method of this builder to DELETE.

Returns:HttpRequest.Builder

this builder

expectContinueback to summary
public HttpRequest.Builder expectContinue(boolean enable)

Requests the server to acknowledge the request before sending the body. This is disabled by default. If enabled, the server is requested to send an error response or a 100 Continue response before the client sends the request body. This means the request publisher for the request will not be invoked until this interim response is received.

Parameters
enable:boolean

true if Expect continue to be sent

Returns:HttpRequest.Builder

this builder

GETback to summary
public HttpRequest.Builder GET()

Sets the request method of this builder to GET. This is the default.

Returns:HttpRequest.Builder

this builder

HEADback to summary
public default HttpRequest.Builder HEAD()

Sets the request method of this builder to HEAD.

Implementation Specification

The default implementation is expected to have the same behaviour as: return method("HEAD", BodyPublishers.noBody());

Returns:HttpRequest.Builder

this builder

Since
18
headerback to summary
public HttpRequest.Builder header(String name, String value)

Adds the given name value pair to the set of headers for this request. The given value is added to the list of values for that name.

Implementation Note

An implementation may choose to restrict some header names or values, as the HTTP Client may determine their value itself. For example, "Content-Length", which will be determined by the request Publisher. In such a case, an implementation of HttpRequest.Builder may choose to throw an IllegalArgumentException if such a header is passed to the builder.

Parameters
name:String

the header name

value:String

the header value

Returns:HttpRequest.Builder

this builder

Exceptions
IllegalArgumentException:
if the header name or value is not valid, see RFC 7230 section-3.2, or the header name or value is restricted by the implementation.
headersback to summary
public HttpRequest.Builder headers(String... headers)

Adds the given name value pairs to the set of headers for this request. The supplied String instances must alternate as header names and header values. To add several values to the same name then the same name must be supplied with each new value.

Parameters
headers:String[]

the list of name value pairs

Returns:HttpRequest.Builder

this builder

Exceptions
IllegalArgumentException:
if there are an odd number of parameters, or if a header name or value is not valid, see RFC 7230 section-3.2, or a header name or value is restricted by the implementation.
methodback to summary
public HttpRequest.Builder method(String method, HttpRequest.BodyPublisher bodyPublisher)

Sets the request method and request body of this builder to the given values.

API Note

The noBody request body publisher can be used where no request body is required or appropriate. Whether a method is restricted, or not, is implementation specific. For example, some implementations may choose to restrict the CONNECT method.

Parameters
method:String

the method to use

bodyPublisher:HttpRequest.BodyPublisher

the body publisher

Returns:HttpRequest.Builder

this builder

Exceptions
IllegalArgumentException:
if the method name is not valid, see RFC 7230 section-3.1.1, or the method is restricted by the implementation.
POSTback to summary
public HttpRequest.Builder POST(HttpRequest.BodyPublisher bodyPublisher)

Sets the request method of this builder to POST and sets its request body publisher to the given value.

Parameters
bodyPublisher:HttpRequest.BodyPublisher

the body publisher

Returns:HttpRequest.Builder

this builder

PUTback to summary
public HttpRequest.Builder PUT(HttpRequest.BodyPublisher bodyPublisher)

Sets the request method of this builder to PUT and sets its request body publisher to the given value.

Parameters
bodyPublisher:HttpRequest.BodyPublisher

the body publisher

Returns:HttpRequest.Builder

this builder

setHeaderback to summary
public HttpRequest.Builder setHeader(String name, String value)

Sets the given name value pair to the set of headers for this request. This overwrites any previously set values for name.

Parameters
name:String

the header name

value:String

the header value

Returns:HttpRequest.Builder

this builder

Exceptions
IllegalArgumentException:
if the header name or value is not valid, see RFC 7230 section-3.2, or the header name or value is restricted by the implementation.
timeoutback to summary
public HttpRequest.Builder timeout(Duration duration)

Sets a timeout for this request. If the response is not received within the specified timeout then an HttpTimeoutException is thrown from HttpClient::send or HttpClient::sendAsync completes exceptionally with an HttpTimeoutException. The effect of not setting a timeout is the same as setting an infinite Duration, i.e. block forever.

Parameters
duration:Duration

the timeout duration

Returns:HttpRequest.Builder

this builder

Exceptions
IllegalArgumentException:
if the duration is non-positive
uriback to summary
public HttpRequest.Builder uri(URI uri)

Sets this HttpRequest's request URI.

Parameters
uri:URI

the request URI

Returns:HttpRequest.Builder

this builder

Exceptions
IllegalArgumentException:
if the URI scheme is not supported
versionback to summary
public HttpRequest.Builder version(HttpClient.Version version)

Sets the preferred HttpClient.Version for this request.

The corresponding HttpResponse should be checked for the version that was actually used. If the version is not set in a request, then the version requested will be that of the sending HttpClient.

Parameters
version:HttpClient.Version

the HTTP protocol version requested

Returns:HttpRequest.Builder

this builder