Adding Parameters to Java HttpClient Requests – 向Java HttpClient请求添加参数

最后修改: 2022年 6月 7日

1. Introduction


In this tutorial, we’ll discuss adding parameters to the Java HttpClient requests.

在本教程中,我们将讨论向Java HttpClient请求添加参数。

The Java HTTPClient is available as a built-in functionality from Java 11. Therefore, we can send HTTP requests without using third-party libraries like Apache HttpClient and OkHttp.

Java HTTPClient从Java 11开始就可以作为一个内置功能。因此,我们可以发送HTTP请求,而无需使用第三方库,如Apache HttpClientOkHttp

2. Adding Parameters


HttpRequest.Builder helps us to easily create HTTP requests and add parameters using the builder pattern.


The Java HttpClient API does not provide any methods to add query parameters. Although we could make use of third-party libraries like URIBuilder from Apache HttpClient to build a request URI string. Let´s see what it would be like to use only the functionality added in Java 11:

Java HttpClient API并没有提供任何方法来添加查询参数。尽管我们可以利用第三方库,如URIBuilder,从Apache HttpClient来构建一个请求URI字符串。让我们看看只使用Java 11中添加的功能会是什么样子。

HttpRequest request = HttpRequest.newBuilder()

Notice that we have set the version() method to use HTTP version 2. The Java HTTPClient uses HTTP 2 by default. However, if servers do not support requests with HTTP 2,  the version will automatically be downgraded to HTTP 1.1.

请注意,我们已经将version()方法设置为使用HTTP版本2。Java的HTTPClient默认使用HTTP 2。然而,如果服务器不支持HTTP 2的请求,版本将自动降级为HTTP 1.1。

Also, we have used GET() as the HTTP request method which is the default. If we do not specify the HTTP request method, the default method GET would be used.


Finally, we can also write the same request in a concise form with the default configuration:


HttpRequest request = HttpRequest.newBuilder()

3. Conclusion


In this example, we covered how to add parameters to the Java HTTPClient requests. Also, the implementations of all these examples and code snippets are available over on GitHub.

在这个例子中,我们介绍了如何向Java HTTPClient请求添加参数。另外,所有这些例子的实现和代码片段都可以在GitHub上找到

In the examples, we’ve used sample REST endpoints provided by