Java_Magazine_NovemberDecember_2018

(singke) #1

40


//java at present/


httpURLConnection.setRequestMethod("GET");

try (BufferedReader in = new BufferedReader(new
InputStreamReader(httpURLConnection.getInputStream()))) {
String response = in.lines().collect(Collectors.joining());
System.out.println(response);
}

This example is very simple; the Stream API makes it more pleasant to read and work with.
However, this API has some deficiencies. It’s not straightforward to use for handling common
requirements such as managing time-outs, cookies, sessions, and HTTP request parameters or
working with proxies.
In addition, the old HttpURLConnection API has design problems:
■■It is verbose to use, and simple requests require a lot of setup.
■■It supports only blocking I/O. In other words, the thread executing the code must wait for the
I/O to complete, and that thread cannot be used to run other tasks.
■■It doesn’t embrace the new functional-style programming that was delivered in Java 8.
■■It is based on configurations using “setter” methods that partially change the state of an
object. Modern APIs have adopted a chainable builder pattern to configure complex objects,
which produces code that is easier to follow.
Most of these limitations have been fixed in JDK 11. In fact, the new HTTP Client library was
introduced in JDK 9 as an incubator project. This means that the library got an opportunity to be
polished and tested before its official integration in JDK 11.
The new library supports nonblocking I/O and data types such as CompletableFuture,
Optional, and the new Date and Time APIs that were introduced in Java 8.
The API consists of four main classes and interfaces:
■■HttpClient: The entry point for using the API
■■HttpRequest: A request to be sent via the HttpClient
Free download pdf