To request an HTTP resource over the network, you'll need to call either of the methods send() or sendAsync() on the HttpClient instance. The send() method sends a request and receives its response synchronously; it will block until these tasks are not complete. The method sendAsync() communicates with a server asynchronously; it sends a request and immediately returns with CompletableFuture.
Before I include examples of the send() and sendAsync() methods, it is important to understand the other two classes: HttpRequest and HttpResponse. I'll cover these methods (send() and sendAsync()) in the section on HttpResponse.
Here's a quick list of the important methods of the HttpClient class:
Method Return Type |
Method Name |
Method Description |
abstract Optional<Authenticator> |
authenticator() |
Returns Optional containing the Authenticator instance set on this client |
abstract Optional<Executor> |
executor() |
Returns Optional containing this client's Executor |
abstract HttpClient.Redirect |
followRedirects() |
Returns the followRedirects policy for this client |
static HttpClient.Builder |
newBuilder() |
Creates a new HttpClient builder |
static HttpClient |
newHttpClient() |
Returns a new HttpClient with default settings |
WebSocket.Builder |
newWebSocketBuilder() |
Creates a new WebSocket builder (optional operation) |
abstract Optional<ProxySelector> |
proxy() |
Returns Optional containing the ProxySelector instance supplied to this client |
abstract <T> HttpResponse<T> |
send (HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) |
Sends the given request using this client, blocking, if necessary, to get the response |
abstract <T> CompletableFuture<HttpResponse<T>> |
sendAsync (HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) |
Sends the given request asynchronously, using this client with the given response body handler |
abstract <T> CompletableFuture<HttpResponse<T>> |
sendAsync (HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler, HttpResponse.PushPromiseHandler<T> pushPromiseHandler) |
Sends the given request asynchronously, using this client with the given response body handler and push promise handler |
abstract SSLContext |
sslContext() |
Returns this client's SSLContext |
abstract SSLParameters |
sslParameters() |
Returns a copy of this client's SSLParameters |
abstract HttpClient.Version |
version() |
Returns the preferred HTTP protocol version for this client |
The next step is to work with the HttpRequest class to define the details of the request.