Open pangiann opened 2 years ago
See: https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html
An HttpClient provides configuration information, and resource sharing, for all requests sent through it.
An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder. The builder can be used to configure per-client state, like:
For 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();
See: https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.html
Now that we've configured the http client we want to create an HTTP request to send it to a server.
An HttpRequest instance is built through an HttpRequest builder. An HttpRequest builder is obtained from one of the newBuilder methods. We can set:
A body. Request bodies are provided through a BodyPublisher supplied to one of the POST, PUT or method methods.
Once all required parameters have been set in the builder, build will return the HttpRequest. Builders can be copied and modified many times in order to build multiple related requests that differ in some parameters.
For example:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://foo.com/"))
.build();
Now, our newly created request is ready to be send. 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. The sendAsync method returns immediately with a CompletableFutureΤhis handler dictates how the httpresponse will interpret the response body. Implementations of BodyHandler that implement various useful handlers, such as handling the response body as a String, or streaming the response body to a file.
For example:
// Receives the response body as a String
HttpResponse<String> response = client
.send(request, BodyHandlers.ofString());
An HttpResponse is not created directly, but rather returned as a result of sending an HttpRequest. An HttpResponse is made available when the response status code and headers have been received, and typically after the response body has also been completely received.
This class provides methods for accessing the response:
statusCode()
headers()
body()
During the creation of the hangman game we came across the situation of an http request in Java.
GET
request using the openlibrary API in order to get a book's description from the millions they offer. https://github.com/pangiann/hangman/issues/1#issuecomment-1000807869Here we'll document which library we will use and how to create an http get request.