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

最后修改: 2022年 6月 7日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

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

2.添加参数

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

HttpRequest.Builder帮助我们轻松创建HTTP请求,并使用构建器模式添加参数。

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()
  .version(HttpClient.Version.HTTP_2)
  .uri(URI.create("https://postman-echo.com/get?param1=value1&param2=value2"))
  .GET()
  .build();

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.

另外,我们使用了GET()作为HTTP请求方法,这是默认的。如果我们不指定HTTP请求方法,将使用默认的GET方法。

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

最后,我们也可以用默认配置以简洁的形式写出同样的请求。

HttpRequest request = HttpRequest.newBuilder()
  .uri(URI.create("https://postman-echo.com/get?param1=value1&param2=value2"))
  .build();

3. Conclusion

3.总结

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 https://postman-echo.com.

在这些例子中,我们使用了https://postman-echo.com.提供的REST端点样本。