Quick Contact

    Hibernate

    Apache HttpClient PUT HTTP Request Example

    In this quick article, we will discuss step by step how to use Apache HttpClient 4.5 to make an HTTP PUT request. The HTTP PUT Request Method requests that the server accepts and stores the entity enclosed in the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI.

    HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GET, HEAD, POST, PUT, DELETE, TRACE, and OPTIONS. There is a specific class for each method type.: HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions.

    In this example, we will use HttpPut class to handle PUT HTTP method.

    Using the Apache HttpClient

    The Apache HttpClient library allows handling HTTP requests. To use this library add a dependency to your Maven or Gradle build file. You find the latest version here: https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

    We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project in order to make HTTP PUT request method.

    	< dependency>
    	< groupId>org.apache.httpcomponents< /groupId>
    	< artifactId>httpclient< /artifactId>
    	< version>4.5< /version>
    	< /dependency>
    

    Development Steps

    Let’s create a step by step example to make an HTTP PUT request using HttpClient.

    1. Create instance of CloseableHttpClient using helper class HttpClients.

      CloseableHttpClienthttpclient=HttpClients.createDefault()

      The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

    2. Create a basic PUT request

      HttpPuthttpPut=newHttpPut(“http://localhost:8080/api/v1/users/5”);

    3. Add headers to PUT HTTP Request

      HttpPuthttpPut=newHttpPut("http://localhost:8080/api/v1/users/5");
      httpPut.setHeader("Accept", "application/json");
      httpPut.setHeader("Content-type", "application/json");
      
    4. Add JSON Data to PUT request

      Stringjson="{\r\n"+
      "\"firstName\": \"Rajan\",\r\n"+
      "\"lastName\": \"Sharma\",\r\n"+
      "\"emailId\": \"rajan12345@gmail.com\",\r\n"+
      "\"createdAt\": \"2021-09-11T11:19:56.000+0000\",\r\n"+
      "\"createdBy\": \"Rajan\",\r\n"+
      "\"updatedAt\": \"2021-09-11T11:26:31.000+0000\",\r\n"+
      "\"updatedby\": \"Rajan\"\r\n"+
      "}";
      StringEntitystringEntity=newStringEntity(json);
      httpPut.setEntity(stringEntity);
      
    5. Create a custom response handler

      ResponseHandler< String>responseHandler= response -> {
      int status =response.getStatusLine().getStatusCode();
      if (status >=200&& status <300) {
      HttpEntity entity =response.getEntity();
      return entity !=null?EntityUtils.toString(entity) :null;
          } else {
      thrownewClientProtocolException("Unexpected response status: "+ status);
          }
      };
      
    6. Send a basic POST request via execute() Method

      StringresponseBody=httpclient.execute(httpPut, responseHandler);

    HttpClient HTTP PUT Request Method Example

    Let’s discuss how to use HttpClient in real-time projects. Consider we have deployed Spring boot Restful CRUD APIs. Check out this article – Spring Boot 2 + hibernate 5 + CRUD REST API Tutorial.

    In the following example, we send a resource to http://localhost:8080/api/v1/users/5. This resource accepts the request JSON, process it and store it into a database. This service also returns a response with an updated resource.In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.

    packagecom.tutorial.ducatindia.httpclient.examples;

    	importjava.io.IOException;
    
    	importorg.apache.http.HttpEntity;
    	importorg.apache.http.client.ClientProtocolException;
    	importorg.apache.http.client.ResponseHandler;
    	importorg.apache.http.client.methods.HttpPut;
    	importorg.apache.http.entity.StringEntity;
    	importorg.apache.http.impl.client.CloseableHttpClient;
    	importorg.apache.http.impl.client.HttpClients;
    	importorg.apache.http.util.EntityUtils;
    
    	/**
    	 * This example demonstrates the use of {@linkHttpPut} request method.
    	 * @authorRajanFadatare
    	 */
    
    	publicclassPUTRequestExample {
    
    	publicstaticvoidmain(String[] args) throwsIOException {
    	putUser();
    	    }
    
    	publicstaticvoidputUser() throwsIOException {
    	try (CloseableHttpClienthttpclient=HttpClients.createDefault()) {
    	HttpPuthttpPut=newHttpPut("http://localhost:8080/api/v1/users/5");
    	httpPut.setHeader("Accept", "application/json");
    	httpPut.setHeader("Content-type", "application/json");
    	Stringjson="{\r\n"+"\"firstName\": \"Rajan\",\r\n"+"\"lastName\": \"Sharma\",\r\n"+
    	"\"emailId\": \"rajan12345@gmail.com\",\r\n"+
    	"\"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n"+"\"createdBy\": \"Rajan\",\r\n"+
    	"\"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n"+"\"updatedby\": \"Rajan\"\r\n"+
    	"}";
    	StringEntitystringEntity=newStringEntity(json);
    	httpPut.setEntity(stringEntity);
    
    	System.out.println("Executing request "+httpPut.getRequestLine());
    
    	// Create a custom response handler
    	ResponseHandler< String>responseHandler= response -> {
    	int status =response.getStatusLine().getStatusCode();
    	if (status >=200&& status <300) {
    	HttpEntity entity =response.getEntity();
    	return entity !=null?EntityUtils.toString(entity) :null;
    	                } else {
    	thrownewClientProtocolException("Unexpected response status: "+ status);
    	                }
    	            };
    	StringresponseBody=httpclient.execute(httpPut, responseHandler);
    	System.out.println("----------------------------------------");
    	System.out.println(responseBody);
    	        }
    	    }
    	}
    
    

    Output

    Executing request PUT http://localhost:8080/api/v1/users/5 HTTP/1.1

    —————————————-

    {“id”:5,”firstName”:”Rajan”,”lastName”:”Sharma”,”emailId”:”rajan12345@gmail.com”,

    “createdAt”:”2021-09-11T11:19:56.000+0000″,”createdBy”:”Ramesh”,

    “updatedAt”:”2021-10-29T09:43:13.756+0000″,”updatedby”:”Ramesh”}

    More Examples

    In the following example, we put data into the resource http://httpbin.org/put. This resources acknowledges the data and returns a JSON object which we’ll simply print to the console.

    packagecom.tutorial.ducatindia.httpclient.examples;

    	importjava.io.IOException;
    
    	importorg.apache.http.HttpEntity;
    	importorg.apache.http.client.ClientProtocolException;
    	importorg.apache.http.client.ResponseHandler;
    	importorg.apache.http.client.methods.HttpPut;
    	importorg.apache.http.entity.StringEntity;
    	importorg.apache.http.impl.client.CloseableHttpClient;
    	importorg.apache.http.impl.client.HttpClients;
    	importorg.apache.http.util.EntityUtils;
    
    	/**
    	 * This example demonstrates the use of {@linkHttpPut} request method.
    	 * 
    	 * @authorRajanFadatare
    	 */
    
    	publicclassPUTRequestExample {
    
    	publicstaticvoidmain(String[] args) throwsIOException {
    	put();
    	    }
    
    	publicstaticvoidput() throwsIOException {
    	try (CloseableHttpClienthttpclient=HttpClients.createDefault()) {
    	HttpPuthttpPut=newHttpPut("http://httpbin.org/put");
    	httpPut.setEntity(newStringEntity("Hello, World"));
    
    	System.out.println("Executing request "+httpPut.getRequestLine());
    
    	// Create a custom response handler
    	ResponseHandler< String>responseHandler= response -> {
    	int status =response.getStatusLine().getStatusCode();
    	if (status >=200&& status <300) {
    	HttpEntity entity =response.getEntity();
    	return entity !=null?EntityUtils.toString(entity) :null;
    	                } else {
    	thrownewClientProtocolException("Unexpected response status: "+ status);
    	                }
    	            };
    	StringresponseBody=httpclient.execute(httpPut, responseHandler);
    	System.out.println("----------------------------------------");
    	System.out.println(responseBody);
    	        }
    	    }
    
    	}
    

    Output

    Executing request PUT http://httpbin.org/put HTTP/1.1

    —————————————-

    	{
    	"args": {}, 
    	"data": "Hello, World", 
    	"files": {}, 
    	"form": {}, 
    	"headers": {
    	"Accept-Encoding": "gzip,deflate", 
    	"Connection": "close", 
    	"Content-Length": "12", 
    	"Content-Type": "text/plain; charset=ISO-8859-1", 
    	"Host": "httpbin.org", 
    	"User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
    	  }, 
    	"json": null, 
    	"origin": "49.35.12.218", 
    	"url": "http://httpbin.org/put"
    	}
    

    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.