


Use the new HTTP/2 Client in Java 11 to send HTTP requests and handle responses
Use the new HTTP/2 Client in Java 11 to send HTTP requests and handle responses
- Introduction
With the release of Java 11, Java introduces a new HTTP/2 Client API to replace the old HttpURLConnection and HttpClient. The new API provides a simpler and more efficient way to send HTTP requests and handle responses. In this article, we will explore the new HTTP/2 Client API in Java 11, including how to send GET requests, POST requests, and how to handle responses. - Send GET request
Sending a GET request is one of the most common HTTP operations. Here is a sample code to send a GET request using the new HTTP/2 Client API in Java 11:
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class HttpClientExample { public static void main(String[] args) throws Exception { // 创建一个HTTP/2 Client HttpClient client = HttpClient.newHttpClient(); // 创建一个GET请求 HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET() .build(); // 发送请求并处理响应 HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 打印响应结果 System.out.println("Response Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } }
In the above sample code, we first create an HttpClient object and then create A GET request is sent through the send() method and returns an HttpResponse object. Finally, we can obtain the response status code and response body through the HttpResponse object.
- Send a POST request
Sending a POST request is another common HTTP operation. Here is a sample code to send a POST request using the new HTTP/2 Client API in Java 11:
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpHeaders; import java.net.http.HttpResponse.BodyHandlers; public class HttpClientExample { public static void main(String[] args) throws Exception { // 创建一个HTTP/2 Client HttpClient client = HttpClient.newHttpClient(); // 创建一个POST请求 HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{"key": "value"}")) .build(); // 发送请求并处理响应 HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 打印响应结果 System.out.println("Response Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } }
In the above sample code, we first create an HttpClient object and then create A POST request, and sends the request through the send() method and returns an HttpResponse object. We can specify the content of the request body through the parameters of the POST method. For example, here we send a JSON string as the request body.
- Handling responses
The new HTTP/2 Client API in Java 11 provides multiple methods to handle responses. In the sample code above, we used HttpResponse.BodyHandlers.ofString() to convert the response body to a string. In addition to ofString(), there are other BodyHandlers that can process the response body according to the specific response content type, such as ofByteArray(), ofInputStream(), etc.
In addition to processing the response body, we can also obtain other response information, such as response headers, response status codes, etc. The following is some sample code for processing responses:
// 获取响应头 HttpHeaders headers = response.headers(); headers.map().forEach((k, v) -> System.out.println(k + ": " + v)); // 获取响应状态码 int statusCode = response.statusCode(); // 判断响应是否成功 if (statusCode == 200) { System.out.println("Request succeeded"); } else { System.out.println("Request failed"); }
The above code shows how to obtain the response header, response status code, and determine whether the request is successful based on the status code.
- Summary
Through this article, we learned how to use the new HTTP/2 Client API in Java 11 to send HTTP requests and handle responses. The new API provides a simpler and more efficient way to perform HTTP operations. I hope this article will help you understand and use the new HTTP/2 Client API.
The above is the detailed content of Use the new HTTP/2 Client in Java 11 to send HTTP requests and handle responses. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Recently, LG Display announced that its 27-inch 480Hz QHD gaming OLED panel has officially entered mass production. This panel has created a new high in refresh rate and response speed among OLED products. The 480Hz refresh rate is paired with a GtG grayscale response time of 0.02ms, which is a step further than the previous record of 0.03ms, bringing the ultimate experience to game types such as FPS and racing. . The new panel optimizes LG Display’s META Technology to improve the luminous efficiency of OLED materials. The image quality is enhanced and specular reflection is greatly reduced. The four-sided frameless design expands the field of view and brings an immersive experience. Pixel structure optimization WRGB pixel structure is optimized for gaming and document editing needs. Text display is clearer

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.
