public abstract class HttpRequest extends Object
HttpRequest
s are built from HttpRequest
builder
s. HttpRequest
builders are obtained from a HttpClient
by calling HttpClient.request
, or
by calling HttpRequest.create
which returns a
builder on the default client.
A request's URI
, headers and body can be set. Request bodies
are provided through a HttpRequest.BodyProcessor
object. Once all required
parameters have been set in the builder, one of the builder methods should be
called, which sets the request method and returns a HttpRequest
.
These methods are GET
, POST
and PUT
which return a GET, POST or
PUT request respectively. Alternatively, method
can be called to set an arbitrary
method type (and return a HttpRequest
). Builders can also be copied
and modified multiple times in order to build multiple related requests that
differ in some parameters.
Two simple, example HTTP interactions are shown below:
// GET
HttpResponse response = HttpRequest
.create(new URI("http://www.foo.com"))
.headers("Foo", "foovalue", "Bar", "barvalue")
.GET()
.response();
int statusCode = response.statusCode();
String responseBody = response.body(asString());
// POST
response = HttpRequest
.create(new URI("http://www.foo.com"))
.body(fromString("param1=foo,param2=bar"))
.POST()
.response();
The request is sent and the response obtained by calling one of the following methods.
response
blocks until the entire request has been
sent and the response status code and headers have been received.responseAsync
sends the request and receives the
response asynchronously. Returns immediately with a
CompletableFuture
<HttpResponse
>.multiResponseAsync
sends the request asynchronously, expecting multiple responses. This
capability is of most relevance to HTTP/2 server push, but can be used for
single responses (HTTP/1.1 or HTTP/2) also.Once a request has been sent, it is an error to try and send it again.
Once a HttpResponse
is received, the headers and response code are
available. The body can then be received by calling one of the body methods
on HttpResponse
.
See below for discussion of synchronous versus asynchronous usage.
Request bodies
Request bodies are sent using one of the request processor implementations
below provided in HttpRequest
, or else a custom implementation can be
used.
fromByteArray(byte[])
from byte arrayfromByteArrays(Iterator)
from an iterator of byte arraysfromFile(Path)
from the file located
at the given PathfromString(String)
from a String fromInputStream(InputStream)
request body from InputStreamnoBody()
no request body is sentResponse bodies
Responses bodies are handled by the HttpResponse.BodyProcessor
<T>
supplied to the HttpResponse.body
and HttpResponse.bodyAsync
methods. Some implementations of
HttpResponse.BodyProcessor
are provided in HttpResponse
:
HttpResponse.asByteArray()
stores the body in a byte arrayHttpResponse.asString()
stores the body as a String HttpResponse.asFile(java.nio.file.Path)
stores the body in a
named fileHttpResponse.ignoreBody()
ignores any received response body The output of a response processor is the response body, and its
parameterized type T
determines the type of the body object returned
from HttpResponse.body
and HttpResponse.bodyAsync
. Therefore,
as an example, the second response processor in the list above has the type
HttpResponse.BodyProcessor<String>
which means the type returned by
HttpResponse.body()
is a String. Response processors can be defined
to return potentially any type as body.
Multi responses
With HTTP/2 it is possible for a server to return a main response and zero
or more additional responses (known as server pushes) to a client-initiated
request. These are handled using a special response processor called HttpResponse.MultiProcessor
.
Blocking/asynchronous behavior and thread usage
There are two styles of request sending: synchronous and
asynchronous. response
blocks the calling thread
until the request has been sent and the response received.
responseAsync
is asynchronous and returns
immediately with a CompletableFuture
<HttpResponse
> and when this object completes (in a background thread) the
response has been received.
multiResponseAsync
is the variant for multi responses and is also asynchronous.
CompletableFutures can be combined in different ways to declare the dependencies among several asynchronous tasks, while allowing for the maximum level of parallelism to be utilized.
Security checks
If a security manager is present then security checks are performed by
the response()
and responseAsync()
methods. A URLPermission
or SocketPermission
is required to
access any destination origin server and proxy server utilised. URLPermissions
should be preferred in policy files over SocketPermissions given the more
limited scope of URLPermission. Permission is always implicitly granted to a
system's default proxies. The URLPermission form used to access proxies uses
a method parameter of "CONNECT" (for all kinds of proxying) and a url string
of the form "socket://host:port" where host and port specify the proxy's
address.
Examples
import static java.net.http.HttpRequest.*; import static java.net.http.HttpResponse.*; //Simple blocking HttpResponse r1 = HttpRequest.create(new URI("http://www.foo.com/")) .GET() .response(); int responseCode = r1.statusCode()); String body = r1.body(asString()); HttpResponse r2 = HttpRequest.create(new URI("http://www.foo.com/")) .GET() .response(); System.out.println("Response was " + r1.statusCode()); Path body1 = r2.body(asFile(Paths.get("/tmp/response.txt"))); // Content stored in /tmp/response.txt HttpResponse r3 = HttpRequest.create(new URI("http://www.foo.com/")) .body(fromString("param1=1, param2=2")) .POST() .response(); Void body2 = r3.body(ignoreBody()); // body is Void in this case
Asynchronous Example
All of the above examples will work asynchronously, if responseAsync()
is used instead of response()
in which case the
returned object is a CompletableFuture<HttpResponse>
instead of
HttpResponse
. The following example shows how multiple requests can
be sent asynchronously. It also shows how dependent asynchronous operations
(receiving response, and receiving response body) can be chained easily using
one of the many methods in CompletableFuture
.
// fetch a list of target URIs asynchronously and store them in Files.
List<URI> targets = ...
List<CompletableFuture<File>> futures = targets
.stream()
.map(target -> {
return HttpRequest
.create(target)
.GET()
.responseAsync()
.thenCompose(response -> {
Path dest = Paths.get("base", target.getPath());
if (response.statusCode() == 200) {
return response.bodyAsync(asFile(dest));
} else {
return CompletableFuture.completedFuture(dest);
}
})
// convert Path -> File
.thenApply((Path dest) -> {
return dest.toFile();
});
})
.collect(Collectors.toList());
// all async operations waited for here
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0]))
.join();
// all elements of futures have completed and can be examined.
// Use File.exists() to check whether file was successfully downloaded
Modifier and Type | Class | Description |
---|---|---|
static interface |
HttpRequest.BodyProcessor |
A request processor which obtains the request body from some source.
|
static class |
HttpRequest.Builder |
A builder of
HttpRequest s. |
Modifier and Type | Method | Description |
---|---|---|
abstract HttpClient |
client() |
Returns this request's
HttpClient . |
static HttpRequest.Builder |
create(URI uri) |
Creates a HttpRequest builder from the default HttpClient.
|
abstract boolean |
expectContinue() |
Returns this request's
expect continue setting. |
abstract HttpClient.Redirect |
followRedirects() |
Returns the follow-redirects setting for this request.
|
static HttpRequest.BodyProcessor |
fromByteArray(byte[] buf) |
Returns a request processor whose body is the given byte array.
|
static HttpRequest.BodyProcessor |
fromByteArray(byte[] buf,
int offset,
int length) |
Returns a request processor whose body is the content of the given byte
array length bytes starting from the specified offset.
|
static HttpRequest.BodyProcessor |
fromByteArrays(Iterator<byte[]> iter) |
A request processor that takes data from an Iterator of byte arrays.
|
static HttpRequest.BodyProcessor |
fromFile(Path path) |
A request processor that takes data from the contents of a File.
|
static HttpRequest.BodyProcessor |
fromInputStream(InputStream stream) |
A request processor that reads its data from an InputStream.
|
static HttpRequest.BodyProcessor |
fromString(String body) |
Returns a request processor whose body is the given String, converted
using the
ISO_8859_1
character set. |
static HttpRequest.BodyProcessor |
fromString(String s,
Charset charset) |
Returns a request processor whose body is the given String, converted
using the given character set.
|
abstract HttpHeaders |
headers() |
The (user-accessible) request headers that this request was (or will be)
sent with.
|
abstract String |
method() |
Returns the request method for this request.
|
abstract <U> CompletableFuture<U> |
multiResponseAsync(HttpResponse.MultiProcessor<U> rspproc) |
Sends the request asynchronously expecting multiple responses.
|
static HttpRequest.BodyProcessor |
noBody() |
A request processor which sends no request body.
|
abstract HttpResponse |
response() |
Returns the response to this request, by sending it and blocking if
necessary to get the response.
|
abstract CompletableFuture<HttpResponse> |
responseAsync() |
Sends the request and returns the response asynchronously.
|
abstract URI |
uri() |
Returns this request's request URI.
|
abstract HttpClient.Version |
version() |
Returns the HTTP protocol version that this request will use or used.
|
public static HttpRequest.Builder create(URI uri)
uri
- the request URIpublic abstract HttpClient.Redirect followRedirects()
public abstract HttpResponse response() throws IOException, InterruptedException
HttpResponse
contains the
response status and headers.IOException
- if an I/O error occursInterruptedException
- if the operation was interruptedSecurityException
- if the caller does not have the required
permissionIllegalStateException
- if called more than once or if
responseAsync() called previouslypublic abstract CompletableFuture<HttpResponse> responseAsync()
CompletableFuture
<HttpResponse
>CompletableFuture<HttpResponse>
IllegalStateException
- if called more than once or if response()
called previously.public abstract <U> CompletableFuture<U> multiResponseAsync(HttpResponse.MultiProcessor<U> rspproc)
This method must be given a HttpResponse.MultiProcessor
to
handle the multiple responses.
If a security manager is set, the caller must possess a URLPermission
for the request's URI, method and any user set
headers. The security manager is also checked for each incoming
additional server generated request/response. Any request that fails the
security check, is canceled and ignored.
This method can be used for both HTTP/1.1 and HTTP/2, but in cases where multiple responses are not supported, the MultiProcessor only receives the main response.
The aggregate CompletableFuture
returned from this method
returns a <U>
defined by the HttpResponse.MultiProcessor
implementation supplied. This will typically be a Collection of
HttpResponses or of some response body type.
U
- the aggregate response typerspproc
- the MultiProcessor for the requestCompletableFuture<U>
IllegalStateException
- if the request has already been sent.public abstract String method()
public abstract boolean expectContinue()
expect continue
setting.public abstract URI uri()
public abstract HttpClient client()
HttpClient
.public abstract HttpClient.Version version()
public abstract HttpHeaders headers()
public static HttpRequest.BodyProcessor fromString(String body)
ISO_8859_1
character set.body
- the String containing the bodypublic static HttpRequest.BodyProcessor fromFile(Path path)
path
- the path to the file containing the bodypublic static HttpRequest.BodyProcessor fromString(String s, Charset charset)
s
- the String containing the bodycharset
- the character set to convert the string to bytespublic static HttpRequest.BodyProcessor fromByteArray(byte[] buf)
buf
- the byte array containing the bodypublic static HttpRequest.BodyProcessor fromByteArray(byte[] buf, int offset, int length)
buf
- the byte array containing the bodyoffset
- the offset of the first bytelength
- the number of bytes to usepublic static HttpRequest.BodyProcessor fromByteArrays(Iterator<byte[]> iter)
iter
- an Iterator of byte arrayspublic static HttpRequest.BodyProcessor fromInputStream(InputStream stream)
stream
- an InputStreampublic static HttpRequest.BodyProcessor noBody()
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2016, Oracle and/or its affiliates. All rights reserved.
DRAFT 9-internal+0-2016-10-04-161205.jjg.dev.8159855.tools-spi