Class HttpClientExamples
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 Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionCreates an HTTP client using the Java 11 standard API.getRequest(URI uri) Builds a GET request.postJsonRequest(URI uri, String jsonBody) Builds a POST request with a String body.sendGetRequest(HttpClient client, URI uri) Sends a GET request synchronously and returns the response body.
-
Constructor Details
-
HttpClientExamples
public HttpClientExamples()
-
-
Method Details
-
clientWithTimeout
Creates an HTTP client using the Java 11 standard API.- Returns:
- a configured HTTP client
-
getRequest
Builds a GET request.- Parameters:
uri- the request URI- Returns:
- an HTTP GET request
-
postJsonRequest
Builds a POST request with a String body.- Parameters:
uri- the request URIjsonBody- the JSON body- Returns:
- an HTTP POST request
-
sendGetRequest
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 requesturi- the request URI- Returns:
- the response body
- Throws:
IOException- when the client cannot read the responseInterruptedException- when the sending thread is interrupted
-