Class HttpClientExamples

java.lang.Object
net.jrodolfo.java_evolution.java11.HttpClientExamples

public class HttpClientExamples extends Object
Demonstrates the standard HTTP Client API finalized in Java 11.

Before Java 11, the JDK's main built-in HTTP API was HttpURLConnection, which was old and awkward for modern HTTP usage. Many applications reached for third-party clients to get a fluent API, asynchronous calls, and HTTP/2 support.

The Java 11 HttpClient solves this by providing a standard client with builders, synchronous and asynchronous execution, and modern protocol support. The examples include request creation and synchronous execution. Tests pass in a fake client so the behavior remains deterministic and offline.

  • Constructor Details

    • HttpClientExamples

      public HttpClientExamples()
  • Method Details

    • clientWithTimeout

      public HttpClient clientWithTimeout()
      Creates an HTTP client using the Java 11 standard API.
      Returns:
      a configured HTTP client
    • getRequest

      public HttpRequest getRequest(URI uri)
      Builds a GET request.
      Parameters:
      uri - the request URI
      Returns:
      an HTTP GET request
    • postJsonRequest

      public HttpRequest postJsonRequest(URI uri, String jsonBody)
      Builds a POST request with a String body.
      Parameters:
      uri - the request URI
      jsonBody - the JSON body
      Returns:
      an HTTP POST request
    • sendGetRequest

      public String sendGetRequest(HttpClient client, URI uri) throws IOException, InterruptedException
      Sends a GET request synchronously and returns the response body.

      The HttpClient.send(HttpRequest, HttpResponse.BodyHandler) method is the central Java 11 operation for blocking HTTP calls. The client is provided by the caller so tests can use a deterministic fake client instead of relying on external network access.

      Parameters:
      client - the client used to execute the request
      uri - the request URI
      Returns:
      the response body
      Throws:
      IOException - when the client cannot read the response
      InterruptedException - when the sending thread is interrupted