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

Jul 30, 2023 pm 04:51 PM
java ask response http/

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

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

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

LG mass-produces 27-inch 480Hz QHD gaming OLED panel with record-breaking clarity and response speed LG mass-produces 27-inch 480Hz QHD gaming OLED panel with record-breaking clarity and response speed Sep 01, 2024 pm 03:37 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

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.

See all articles