Home > Java > javaTutorial > body text

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

王林
Release: 2023-08-26 09:45:03
forward
942 people have browsed it

在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>);
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!