Http/2 is a newer version of the Http protocol. Improvements to Http/2 include attention to how data is constructed and transferred between the server and client. In this new version of the Http/2 protocol, separate classes are defined for Httpclients, requests, and responses. The new API makes Http connections easier to maintain, faster, and enables more responsive applications without the need for third-party libraries.
The new API handles HTTP connections through three classes.
In the code snippet below, we need to send a request to a specific URL and receive the response.
<strong>// Create an HttpClient object </strong> <strong> HttpClient </strong>httpClient = <strong>HttpClient.newHttpClient()</strong>; System.out.println(<strong>httpClient.version()</strong>); <strong>// Build a HTTPRequest </strong><strong> HttpRequest </strong>httpRequest = HttpRequest.newBuilder().uri(new URI("https://www.tutorialspoint.com/")).<strong>GET</strong>().build(); <strong>// create a GET request for the given URI</strong> <strong>Map</strong><strong><String, List<String></strong>> headers = httpRequest.headers().map(); headers.forEach((k, v) -> System.out.println(k + "-" + v)); <strong>// Send the request </strong><strong> HttpResponse </strong>httpResponse = httpClient.<strong>send</strong>(httpRequest, HttpResponse.BodyHandler.asString()); <strong>// Output the body of the response </strong> System.out.println("Response: " + httpResponse.<strong>body()</strong>);
The above is the detailed content of What are the different Http/2 client classes in Java 9?. For more information, please follow other related articles on the PHP Chinese website!