Module java.net.http
Package java.net.http

Class HttpClient

java.lang.Object
java.net.http.HttpClient

public abstract classHttpClientextendsObject
An HTTP Client.

AnHttpClient can be used to sendrequests and retrieve theirresponses. An HttpClient is created through abuilder. ThenewBuilder method returns a builder that creates instances of the defaultHttpClient implementation. The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc. Once built, anHttpClient is immutable, and can be used to send multiple requests.

AnHttpClient provides configuration information, and resource sharing, for all requests sent through it.

ABodyHandler must be supplied for eachHttpRequest sent. TheBodyHandler determines how to handle the response body, if any. Once anHttpResponse is received, the headers, response code, and body (typically) are available. Whether the response body bytes have been read or not depends on the type,T, of the response body.

Requests can be sent either synchronously or asynchronously:

  • send(HttpRequest, BodyHandler) blocks until the request has been sent and the response has been received.
  • sendAsync(HttpRequest, BodyHandler) sends the request and receives the response asynchronously. ThesendAsync method returns immediately with aCompletableFuture<HttpResponse>. The CompletableFuture completes when the response becomes available. The returnedCompletableFuture can be combined in different ways to declare dependencies among several asynchronous tasks.

Synchronous Example

   HttpClient client = HttpClient.newBuilder()        .version(Version.HTTP_1_1)        .followRedirects(Redirect.NORMAL)        .connectTimeout(Duration.ofSeconds(20))        .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))        .authenticator(Authenticator.getDefault())        .build();   HttpResponse<String> response = client.send(request, BodyHandlers.ofString());   System.out.println(response.statusCode());   System.out.println(response.body());

Asynchronous Example

   HttpRequest request = HttpRequest.newBuilder()        .uri(URI.create("https://foo.com/"))        .timeout(Duration.ofMinutes(2))        .header("Content-Type", "application/json")        .POST(BodyPublishers.ofFile(Paths.get("file.json")))        .build();   client.sendAsync(request, BodyHandlers.ofString())        .thenApply(HttpResponse::body)        .thenAccept(System.out::println);

Security checks

If a security manager is present then security checks are performed by the HTTP Client's sending methods. An appropriateURLPermission is required to access the destination server, and proxy server if one has been configured. The form of theURLPermission required to access a proxy has amethod parameter of"CONNECT" (for all kinds of proxying) and aURL string of the form"socket://host:port" where host and port specify the proxy's address.

Implementation Note:
If an explicitexecutor has not been set for anHttpClient, and a security manager has been installed, then the default executor will execute asynchronous and dependent tasks in a context that is granted no permissions. Customrequest body publishers,response body handlers,response body subscribers, andWebSocket Listeners, if executing operations that require privileges, should do so within an appropriateprivileged context.
Since:
11
  • Constructor Details

    • HttpClient

      protected HttpClient()
      Creates an HttpClient.
  • Method Details

    • newHttpClient

      public static HttpClient newHttpClient()
      Returns a newHttpClient with default settings.

      Equivalent tonewBuilder().build().

      The default settings include: the "GET" request method, a preference ofHTTP/2, a redirection policy ofNEVER, thedefault proxy selector, and thedefault SSL context.

      Implementation Note:
      The system-wide default values are retrieved at the time theHttpClient instance is constructed. Changing the system-wide values after anHttpClient instance has been built, for instance, by callingProxySelector.setDefault(ProxySelector) orSSLContext.setDefault(SSLContext), has no effect on already built instances.
      Returns:
      a new HttpClient
      Throws:
      UncheckedIOException - if necessary underlying IO resources required tobuild a new HttpClient cannot be allocated.
    • newBuilder

      public static HttpClient.Builder newBuilder()
      Creates a newHttpClient builder.

      Builders returned by this method create instances of the defaultHttpClient implementation.

      Returns:
      anHttpClient.Builder
    • cookieHandler

      public abstract Optional<CookieHandler> cookieHandler()
      Returns anOptional containing this client'sCookieHandler. If noCookieHandler was set in this client's builder, then theOptional is empty.
      Returns:
      anOptional containing this client'sCookieHandler
    • connectTimeout

      public abstract Optional<Duration> connectTimeout()
      Returns anOptional containing theconnect timeout duration for this client. If theconnect timeout duration was not set in the client's builder, then theOptional is empty.
      Returns:
      anOptional containing this client's connect timeout duration
    • followRedirects

      public abstract HttpClient.Redirect followRedirects()
      Returns the follow redirects policy for this client. The default value for client's built by builders that do not specify a redirect policy isNEVER.
      Returns:
      this client's follow redirects setting
    • proxy

      public abstract Optional<ProxySelector> proxy()
      Returns anOptional containing theProxySelector supplied to this client. If no proxy selector was set in this client's builder, then theOptional is empty.

      Even though this method may return an empty optional, the HttpClient may still have a non-exposeddefault proxy selector that is used for sending HTTP requests.

      Returns:
      anOptional containing the proxy selector supplied to this client.
    • sslContext

      public abstract SSLContext sslContext()
      Returns this client'sSSLContext.

      If noSSLContext was set in this client's builder, then thedefault context is returned.

      Returns:
      this client's SSLContext
    • sslParameters

      public abstract SSLParameters sslParameters()
      Returns a copy of this client'sSSLParameters.

      If noSSLParameters were set in the client's builder, then an implementation specific default set of parameters, that the client will use, is returned.

      Returns:
      this client'sSSLParameters
    • authenticator

      public abstract Optional<Authenticator> authenticator()
      Returns anOptional containing theAuthenticator set on this client. If noAuthenticator was set in the client's builder, then theOptional is empty.
      Returns:
      anOptional containing this client'sAuthenticator
    • version

      public abstract HttpClient.Version version()
      Returns the preferred HTTP protocol version for this client. The default value isHttpClient.Version.HTTP_2
      Implementation Note:
      Constraints may also affect the selection of protocol version. For example, if HTTP/2 is requested through a proxy, and if the implementation does not support this mode, then HTTP/1.1 may be used
      Returns:
      the HTTP protocol version requested
    • executor

      public abstract Optional<Executor> executor()
      Returns anOptional containing this client'sExecutor. If noExecutor was set in the client's builder, then theOptional is empty.

      Even though this method may return an empty optional, the HttpClient may still have an non-exposeddefault executor that is used for executing asynchronous and dependent tasks.

      Returns:
      anOptional containing this client'sExecutor
    • send

      public abstract <T> HttpResponse<T> send(HttpRequest request,HttpResponse.BodyHandler<T> responseBodyHandler) throwsIOException,InterruptedException
      Sends the given request using this client, blocking if necessary to get the response. The returnedHttpResponse<T> contains the response status, headers, and body ( as handled by given response body handler ).

      If the operation is interrupted, the defaultHttpClient implementation attempts to cancel the HTTP exchange andInterruptedException is thrown. No guarantee is made as to exactlywhen the cancellation request may be taken into account. In particular, the request might still get sent to the server, as its processing might already have started asynchronously in another thread, and the underlying resources may only be released asynchronously.

      • With HTTP/1.1, an attempt to cancel may cause the underlying connection to be closed abruptly.
      • With HTTP/2, an attempt to cancel may cause the stream to be reset, or in certain circumstances, may also cause the connection to be closed abruptly, if, for instance, the thread is currently trying to write to the underlying socket.

      Type Parameters:
      T - the response body type
      Parameters:
      request - the request
      responseBodyHandler - the response body handler
      Returns:
      the response
      Throws:
      IOException - if an I/O error occurs when sending or receiving
      InterruptedException - if the operation is interrupted
      IllegalArgumentException - if therequest argument is not a request that could have been validly built as specified byHttpRequest.Builder.
      SecurityException - If a security manager has been installed and it deniesaccess to the URL in the given request, or proxy if one is configured. Seesecurity checks for further information.
    • sendAsync

      public 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.

      Equivalent to:sendAsync(request, responseBodyHandler, null).

      Type Parameters:
      T - the response body type
      Parameters:
      request - the request
      responseBodyHandler - the response body handler
      Returns:
      aCompletableFuture<HttpResponse<T>>
      Throws:
      IllegalArgumentException - if therequest argument is not a request that could have been validly built as specified byHttpRequest.Builder.
    • sendAsync

      public 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.

      The returned completable future, if completed successfully, completes with anHttpResponse<T> that contains the response status, headers, and body ( as handled by given response body handler ).

      Push promises received, if any, are handled by the givenpushPromiseHandler. Anull valuedpushPromiseHandler rejects any push promises.

      The returned completable future completes exceptionally with:

      • IOException - if an I/O error occurs when sending or receiving
      • SecurityException - If a security manager has been installed and it deniesaccess to the URL in the given request, or proxy if one is configured. Seesecurity checks for further information.

      The defaultHttpClient implementation returnsCompletableFuture objects that arecancelable.CompletableFuture objectsderived from cancelable futures are themselvescancelable. Invokingcancel(true) on a cancelable future that is not completed, attempts to cancel the HTTP exchange in an effort to release underlying resources as soon as possible. No guarantee is made as to exactlywhen the cancellation request may be taken into account. In particular, the request might still get sent to the server, as its processing might already have started asynchronously in another thread, and the underlying resources may only be released asynchronously.

      • With HTTP/1.1, an attempt to cancel may cause the underlying connection to be closed abruptly.
      • With HTTP/2, an attempt to cancel may cause the stream to be reset.

      Type Parameters:
      T - the response body type
      Parameters:
      request - the request
      responseBodyHandler - the response body handler
      pushPromiseHandler - push promise handler, may be null
      Returns:
      aCompletableFuture<HttpResponse<T>>
      Throws:
      IllegalArgumentException - if therequest argument is not a request that could have been validly built as specified byHttpRequest.Builder.
    • newWebSocketBuilder

      public WebSocket.Builder newWebSocketBuilder()
      Creates a newWebSocket builder (optional operation).

      Example

         HttpClient client = HttpClient.newHttpClient();   CompletableFuture<WebSocket> ws = client.newWebSocketBuilder()           .buildAsync(URI.create("ws://websocket.example.com"), listener);

      Finer control over the WebSocket Opening Handshake can be achieved by using a customHttpClient.

      Example

         InetSocketAddress addr = new InetSocketAddress("proxy.example.com", 80);   HttpClient client = HttpClient.newBuilder()           .proxy(ProxySelector.of(addr))           .build();   CompletableFuture<WebSocket> ws = client.newWebSocketBuilder()           .buildAsync(URI.create("ws://websocket.example.com"), listener);

      Implementation Requirements:
      The default implementation of this method throwsUnsupportedOperationException. Clients obtained throughnewHttpClient() ornewBuilder() return aWebSocket builder.
      Implementation Note:
      Both builder andWebSockets created with it operate in a non-blocking fashion. That is, their methods do not block before returning aCompletableFuture. Asynchronous tasks are executed in thisHttpClient's executor.

      When aCompletionStage returned fromListener.onClose completes, theWebSocket will send a Close message that has the same code the received message has and an empty reason.

      Returns:
      aWebSocket.Builder
      Throws:
      UnsupportedOperationException - if thisHttpClient does not provide WebSocket support