pangiann / hangman

Hangman is a paper and pencil guessing game for two or more players.
0 stars 0 forks source link

[java-httpRequests] Document how to create an http request in Java #2

Open pangiann opened 2 years ago

pangiann commented 2 years ago

During the creation of the hangman game we came across the situation of an http request in Java.

Here we'll document which library we will use and how to create an http get request.

pangiann commented 2 years ago

See: https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html

Http Client

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();
pangiann commented 2 years ago

See: https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.html

HTTP Request

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:

For example:

HttpRequest request = HttpRequest.newBuilder()
         .uri(URI.create("http://foo.com/"))
         .build();
pangiann commented 2 years ago

HTTP send

Now, our newly created request is ready to be send. Requests can be sent either synchronously or asynchronously:

BodyHandler

Τ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());
pangiann commented 2 years ago

Http Response

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: