Java_Magazine_NovemberDecember_2018

(singke) #1

41


//java at present/


■■HttpResponse: The result of an HttpRequest call
■■WebSocket: The entry point for setting up a WebSocket client
Here’s how you can rewrite the previous example to make a simple request:

var httpClient = HttpClient.newHttpClient();
var request
= HttpRequest
.newBuilder(URI.create("http://iteratorlearning.com"))
.build();
HttpResponse<String> response
= httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

You have to admit this code is immediately readable. The new HTTP Client API supports non-
blocking I/O via the sendAsync method, which returns a CompletableFuture. You can use it
as follows:

var httpClient = HttpClient.newHttpClient();
var request
= HttpRequest
.newBuilder(URI.create("http://iteratorlearning.com"))
.build();
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);

If you want to send a POST request, you can use the POST method available in the API. For exam-
ple, the following code creates a POST request consisting of a JSON payload read from the file
data.json and sent to the /post endpoint of http://httpbin.org:
Free download pdf