How to Execute an HTTP PUT Request in Java

In this tutorial, you will learn how to execute an HTTP PUT request in Java. You might also be interested to learn how to execute other HTTP methods. If you are, then please check the following tutorials as well: 

The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.  This method is Idempotent, which means that executing it should not have any side effects.

To execute an HTTP request in Java, we need to have an HTTP client as a dependency. In this tutorial, we will cover the HTTP PUT Request using the  Apache HttpClient.

First, we need to add Maven dependency:

<dependency>
    <groupid>org.apache.httpcomponents</groupid>
    <artifactid>httpclient</artifactid>
    <version>4.5.13</version>
</dependency>


Find other versions here → Apache HTTP Client. If you are not using Maven, you can also download JAR from the location above.

Execute an HTTP PUT request in Java using Apache HTTP client

Below is a simple example of executing an HTTP PUT request in Java.

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpPut;

import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class Test {

  public static void main(String[] args) throws IOException {

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

      HttpPut httpPut = new HttpPut("https://jsonplaceholder.typicode.com/posts/1");
     
      // specify the PUT body to send to the server as part of the request
      httpPut.setEntity(new StringEntity("{\"id\":1,\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"));

      System.out.println("Executing PUT request...");
      HttpResponse response = httpclient.execute(httpPut);

      System.out.println("Status code:" + response.getStatusLine().getStatusCode());

      String responseBody = new BasicResponseHandler().handleResponse(response);

      System.out.println(responseBody);
    }
  }
}
Output: Executing PUT request… Status code:200 { “id”: 1 }
 
Here we used the try-with-resources to create an HttpClient. That means we don’t have to close it after executing the request. The try-with-resources statement ensures that each resource is closed at the end of the statement.
 
We also used the BasicResponseHandler to retrive the response body and response.getStatusLine().getStatusCode() to retrive the response status code.

Execute an HTTP PUT request with headers

We can also add HTTP headers to the request, like in the following example:

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class Test {

  public static void main(String[] args) throws IOException {

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

      HttpUriRequest request = RequestBuilder.put()
              .setUri("https://jsonplaceholder.typicode.com/posts/1")
              .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
              .setHeader("Authorization", "Bearer 123token")
              // add request body
              .setEntity(new StringEntity("{\"id\":1,\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"))
              .build();

      System.out.println("Executing PUT request... ");
      HttpResponse response = httpclient.execute(request);

      System.out.println("Status code: " + response.getStatusLine().getStatusCode());

      String responseString = new BasicResponseHandler().handleResponse(response);

      System.out.println("Response: " + responseString);
    }
  }
}
Output: Executing PUT request… Status code:200 { “id”: 1 }
 
We used the RequestBuilder class to build the request with all the required data (URL, headers, request body).
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *