Apache HttpClient 4.5 HTTP POST Request Method Example
This tutorial demonstrates how to use Apache HttpClient 4.5 to make a 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. The posted data can be, but is not limited to, an annotation for existing resources or data formatted JSON, XML or submitted FORM data. The server can use the posted data to update resources in the database, or process this data.
Maven dependencies
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.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.memorynotfound.apache.httpclient.httmethods</groupId> <artifactId>http-post</artifactId> <version>1.0.0-SNAPSHOT</version> <url>https://memorynotfound.com</url> <name>httpclient - ${project.artifactId}</name> <dependencies> <!-- Apache HttpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
HTTP POST request method example
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. Note: we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient. Next we are using Java 8 lambdas for the ResponseHandler. Here we are evaluating the Http Status code, when everything is ok we return the body of the response which we parse to a String. When the status code is not what we expect, we throw a ClientProtocolException, indicating that the Http POST request method failed. Finally, we print the response body to the console.
package com.memorynotfound.httpclient; 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; import java.io.IOException; /** * This example demonstrates the use of {@link HttpPost} request method. */ public class HttpPostRequestMethodExample { public static void main(String... args) 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 Disconnected from the target VM, address: '127.0.0.1:59995', transport: 'socket' ---------------------------------------- { "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.2 (Java/1.8.0_20)" }, "json": null, "origin": "", "url": "http://httpbin.org/post" }
Download
From:一号门
COMMENTS