Home  >  Article  >  Java  >  What are the different Http/2 client classes in Java 9?

What are the different Http/2 client classes in Java 9?

王林
王林forward
2023-08-26 09:45:03977browse

在Java 9中有哪些不同的Http/2客户端类?

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.

  • HttpClient: It handles the creation and sending of requests.
  • HttpRequest: It is used to construct the request to be sent through HttpClient.
  • HttpResponse: It saves the response of the sent request.

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete