Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Introduction

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

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.

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:

HttpRequest request = HttpRequest.newBuilder()
  .version(HttpClient.Version.HTTP_2)
  .uri(URI.create("https://postman-echo.com/get?param1=value1¶m2=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.

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()
  .uri(URI.create("https://postman-echo.com/get?param1=value1¶m2=value2"))
  .build();

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.

In the examples, we've used sample REST endpoints provided by https://postman-echo.com.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments