Quick Contact

    Hibernate

    Apache HttpClient POST HTTP Request Example

    In this topic, Herewe will discuss step by step how to use Apache HttpClient 4.5 to make an HTTP POST request. The HTTP POST request method requests that the server accepts the entity enclosed in the request as a new subordinate of the web resource identified by the 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 HttpPost class to handle the POST HTTP method.

    Check out Apache HttpClient GET HTTP Request Example

    Using the Apache HttpClient – Add Dependency

    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 POST 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 POST 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 POST request

      HttpPosthttpPost=newHttpPost(“http://localhost:8080/api/v1/users”);

    3. Add headers to Post HTTP Request

      HttpPosthttpPost=newHttpPost("http://localhost:8080/api/v1/users");
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");
      
    4. Add JSON Data to Post request

      Stringjson="{\r\n"+
      "\"firstName\": \"Ranjan\",\r\n"+
      "\"lastName\": \"Sharma\",\r\n"+
      "\"emailId\": \"sharma12345@gmail.com\",\r\n"+
      "\"createdAt\": \"2021-09-11T11:19:56.000+0000\",\r\n"+
      "\"createdBy\": \"Ranjan\",\r\n"+
      "\"updatedAt\": \"2021-09-11T11:26:31.000+0000\",\r\n"+
      "\"updatedby\": \"Ranjan\"\r\n"+
      "}";
      StringEntitystringEntity=newStringEntity(json);
      httpPost.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 basic POST request via execute() Method

      StringresponseBody=httpclient.execute(httpPost, responseHandler);

    HttpClient HTTP POST Request Method Example

    In the following example, we send a resource to http://localhost:8080/api/v1/users. This resource accepts the request JSON, process it and store it into a database. This service also returns a response with a 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.HttpPost;
    	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 {@linkHttpPost} request method.
    	 * @author Ramesh Fadatare
    	 */
    	publicclassHttpPostRequestMethodExample {
    
    	publicstaticvoidmain(String[] args) throwsIOException {
    	postUser();
    	    }
    
    	publicstaticvoidpostUser() throwsIOException {
    	try (CloseableHttpClienthttpclient=HttpClients.createDefault()) {
    	HttpPosthttpPost=newHttpPost("http://localhost:8080/api/v1/users");
    	httpPost.setHeader("Accept", "application/json");
    	httpPost.setHeader("Content-type", "application/json");
    	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);
    	httpPost.setEntity(stringEntity);
    
    	System.out.println("Executing request "+httpPost.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(httpPost, responseHandler);
    	System.out.println("----------------------------------------");
    	System.out.println(responseBody);
    	        }
    	    }
    	}
    

    Output

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

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

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

    	"createdAt":"2021-10-29T09:37:09.821+0000","createdBy":"Ramesh","updatedAt":"2021-10-29T09:37:09.821+0000",
    	"updatedby":"Rajan"}
    

    More Examples

    In the following example, we post data to the resource http://httpbin.org/post. 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.HttpPost;
    	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 {@linkHttpPost} request method.
    	 */
    	publicclassHttpPostRequestMethodExample {
    
    	publicstaticvoidmain(String[] args) throwsIOException {
    	post();
    	    }
    	publicstaticvoidpost() throwsIOException {
    
    	try (CloseableHttpClienthttpclient=HttpClients.createDefault()) {
    	HttpPosthttpPost=newHttpPost("http://httpbin.org/post");
    	httpPost.setEntity(newStringEntity("Hello, World"));
    
    	System.out.println("Executing request "+httpPost.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(httpPost, responseHandler);
    	System.out.println("----------------------------------------");
    	System.out.println(responseBody);
    	        }
    	    }
    	}
    

    Output

    Executing request POST http://httpbin.org/post 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/post"
    	}
    

    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.