Java apache httpclient post request

Apache HttpClient POST request

In this article, we will explore how to execute an HTTP POST request using Apache HttpClient library with example programs.
Setup
For using HttpClient library, you need to add it to your project as per the build tool using below dependency

// GRADLE implementation 'org.apache.httpcomponents:httpclient:4.5.13' // MAVEN org.apache.httpcomponents httpclient 4.5.13  

If you are not using any build tool, then directly add its jar file to the classpath.

To test our program, we need an endpoint URL.
For this article, we will be using a fake web service URL https://jsonplaceholder.typicode.com/posts, along with a body containing the fields of post and their values.

Below are field names and their arbitrary values

"title": "foo", "body": "bar", "userId": "1", "id": 101

If the request is successful, it returns the request body as it is.

Steps
Following are the steps required to execute a POST request using Apache HttpClient.

1. Create a client.
A client is used to send HTTP requests to a URL. This URL is called endpoint URL or simply endpoint.

A client object in HttpClient is created using below syntax

CloseableHttpClient client = HttpClients.createDefault();

At some places, you will also find below code that creates an instance of HttpClient.

CloseableHttpClient client = HttpClientBuilder.create().build();

Both are the same since createDefault() internally calls the same code.
2. Create a request
To execute a request in HttpClient , we need an object of HttpUriRequest .
This is an interface which is implemented by classes that represent HTTP request types such as HttpGet and HttpPost for GET and POST requests respectively.

Since this article shows a POST request, we need to create an object of HttpPost as below

HttpPost request = new HttpPost( "https://jsonplaceholder.typicode.com/posts");

Constructor of HttpPost accepts the endpoint URL at which the data will be posted.

3. Add request body
Request body implies that data that we need to send along with the request.
This data is generally persisted to the database at the backend server. There are two ways to send data in POST request with Apache HttpClient.

A. As key-value pairs
Apache HttpClient allows you to add POST request data in the form of key and value pairs.
HttpPost class has a setEntity() method where you can add a list of parameters to send in request body.
Parameters are added as objects of BasicNameValuePair class, which implements NameValuePair . Example,

List params = new ArrayList<>(); params.add(new BasicNameValuePair("title", "foo"));

B. As json
Instead of adding individual key-value pairs which becomes tedious when the body is large, you can directly provide a json string as request body to the setEntity() method.

Examples of both these methods are given in the next section.

4. Execute request
Once we have a client and a request, it can directly be executed using execute() method of client.

execute() accepts an object of HttpUriRequest , which we created in the last step and returns the response returned by the URL as an object of CloseableHttpResponse as below

CloseableHttpResponse response = client.execute(get);

5. Reading response
CloseableHttpResponse contains a getEntity() method which returns an HttpEntity object, that contains the actual response.

HttpEntity has a getContent() method which returns a java InputStream containing the response.
This Inputstream can be used to read the response using BufferedReader or can be directly converted to a string .

HttpClient POST example
Below is a complete example of executing a POST request with HttpClient using the steps outlined above.
This method uses key-value pairs to add body to the request

// create client CloseableHttpClient client = HttpClients.createDefault(); // create request object HttpPost post = new HttpPost( «https://jsonplaceholder.typicode.com/posts»); try < // create key-value pairs Listparams = new ArrayList<>(); params.add(new BasicNameValuePair(«title», «foo»)); params.add(new BasicNameValuePair(«body», «bar»)); params.add(new BasicNameValuePair(«userId», «1»)); // add to request post.setEntity(new UrlEncodedFormEntity(params)); // get response CloseableHttpResponse response = client.execute(post); // inputstream to bufferedread BufferedReader br = new BufferedReader( new InputStreamReader( response.getEntity().getContent())); String line = null; // read response while( (line = br.readLine())!=null) < System.out.println(line); >> catch (ClientProtocolException e) < e.printStackTrace(); >catch (IOException e)

Below is the response received

Note that setEntity() accepts a parameter of type HttpEntity .
To provide the body as key-value pairs, we provide it an object of UrlEncodedFormEntity , which accepts a list of NameValuePair objects.
UrlEncodedFormEntity converts the list of body parameters as a single String object.
HttpClient json POST
Below code directly adds a json string to the request body. This is useful when the number of body parameters is large or you have an already populated object which can be converted to a string .

// create client CloseableHttpClient client = HttpClients.createDefault(); // create request object HttpPost post = new HttpPost( «https://jsonplaceholder.typicode.com/posts»); try < // define json body String json = ""; // add to request post.setEntity(new StringEntity(json)); post.setHeader("Content-Type", "application/json"); // get response CloseableHttpResponse response = client.execute(post); // inputstream to bufferedread BufferedReader br = new BufferedReader( new InputStreamReader( response.getEntity().getContent())); String line = null; // read response while( (line = br.readLine())!=null) < System.out.println(line); >> catch (ClientProtocolException e) < e.printStackTrace(); >catch (IOException e)

Note that here, we are passing an object of StringEntity to setEntity() method.
This is because setEntity() accepts an object of type HttpEntity , an interface and StringEntity implements it.

Also, note that in this request, we are also setting Content-Type header to “application/json” to inform the server that the request will be containing json data.

Hope the article was useful in explaining how Apache HttpClient can be used to send HTTP POST request containing a body.
This body can be in key-value pairs or in json.

Источник

Java Guides

In this quick article, we 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 .

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.httpcomponentsgroupId> artifactId>httpclientartifactId> version>4.5version> dependency>

Development Steps

1. Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()

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

2. Create a basic POST request

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");

3. Add headers to Post HTTP Request

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users"); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json");

3. Add JSON Data to Post request

String json = "\r\n" + " \"firstName\": \"Ram\",\r\n" + " \"lastName\": \"Jadhav\",\r\n" + " \"emailId\": \"ramesh1234@gmail.com\",\r\n" + " \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + " \"createdBy\": \"Ramesh\",\r\n" + " \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + " \"updatedby\": \"Ramesh\"\r\n" + ">"; StringEntity stringEntity = new StringEntity(json); httpPost.setEntity(stringEntity);

4. 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 < throw new ClientProtocolException("Unexpected response status: " + status); > >;

5. Send basic POST request via execute() Method

String responseBody = httpclient.execute(httpPost, responseHandler);

HttpClient HTTP POST 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. 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.

package com.javadevelopersguide.httpclient.examples; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * This example demonstrates the use of @link HttpPost> request method. * @author Ramesh Fadatare */ public class HttpPostRequestMethodExample < public static void main(String[] args) throws IOException < postUser(); >public static void postUser() throws IOException < try (CloseableHttpClient httpclient = HttpClients.createDefault()) < HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users"); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); String json = "\r\n" + " \"firstName\": \"Ram\",\r\n" + " \"lastName\": \"Jadhav\",\r\n" + " \"emailId\": \"ramesh1234@gmail.com\",\r\n" + " \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + " \"createdBy\": \"Ramesh\",\r\n" + " \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + " \"updatedby\": \"Ramesh\"\r\n" + ">"; StringEntity stringEntity = new StringEntity(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 < throw new ClientProtocolException("Unexpected response status: " + status); > >; String responseBody = httpclient.execute(httpPost, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); > > >

Output

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

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.

package com.javadevelopersguide.httpclient.examples; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * This example demonstrates the use of @link HttpPost> request method. */ public class HttpPostRequestMethodExample < public static void main(String[] args) throws IOException < post(); >public static void post() throws IOException < try (CloseableHttpClient httpclient = HttpClients.createDefault()) < HttpPost httpPost = new HttpPost("http://httpbin.org/post"); httpPost.setEntity(new StringEntity("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 < throw new ClientProtocolException("Unexpected response status: " + status); > >; String responseBody = 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" >

Источник

Читайте также:  Colorama python как использовать
Оцените статью