Home  >  Article  >  Java  >  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

WBOY
WBOYOriginal
2023-07-30 16:51:231310browse

Use the new HTTP/2 Client in Java 11 to send HTTP requests and handle responses

  1. 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.
  2. 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.

  1. 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.

  1. 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.

  1. 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!

Statement:
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