We can indicate the HTTP method that's used by our request using the following methods from HttpRequest.Builder:
- GET(): This method sends the request using the HTTP GET method, as shown in the following example:
HttpRequest requestGet = HttpRequest.newBuilder()
.GET() // can be omitted since it is default
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
- POST(): This method sends the request using the HTTP POST method, as shown in the following example:
HttpRequest requestPost = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{"name": "morpheus","job": "leader"}"))
.uri(URI.create("https://reqres.in/api/users"))
.build();
- PUT(): This method sends the request using the HTTP PUT method, as shown in the following example:
HttpRequest requestPut = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.PUT(HttpRequest.BodyPublishers.ofString(
"{"name": "morpheus","job": "zion resident"}"))
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
- DELETE(): This method sends the request using the HTTP DELETE method, as shown in the following example:
HttpRequest requestDelete = HttpRequest.newBuilder()
.DELETE()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
The client can handle all types of HTTP methods, not only the predefined methods (GET, POST, PUT, and DELETE). To create a request with a different HTTP method, we just need to call method().
The following solution triggers an HTTP PATCH request:
HttpRequest requestPatch = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.method("PATCH", HttpRequest.BodyPublishers.ofString(
"{"name": "morpheus","job": "zion resident"}"))
.uri(URI.create("https://reqres.in/api/users/1"))
.build();
When no request body is required, we can rely on BodyPublishers.noBody(). The following solution uses the noBody() method to trigger an HTTP HEAD request:
HttpRequest requestHead = HttpRequest.newBuilder()
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.uri(URI.create("https://reqres.in/api/users/1"))
.build();
In the case of multiple similar requests, we can rely on the copy() method to copy the builder, as shown in the following snippet of code:
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create("..."));
HttpRequest request1 = builder.copy().setHeader("...", "...").build();
HttpRequest request2 = builder.copy().setHeader("...", "...").build();