Introduction
Apache HttpClient is a powerful and flexible library for handling HTTP requests in Java. It supports various HTTP methods and can handle different types of request bodies, including HTML form data. This tutorial will demonstrate how to send an HTML form POST request using Apache HttpClient.
Maven Dependencies
To use Apache HttpClient, you need to add the following dependency to your pom.xml
file:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3</version>
</dependency>
Example Scenario
We will create a simple Java class that sends a POST request with HTML form data to a specified URL and prints the response.
JSONPlaceholder API
For this example, we will use the JSONPlaceholder API. Although it is primarily used for JSON requests, it will still accept form data for testing purposes. The URL for the POST endpoint is:
https://jsonplaceholder.typicode.com/posts
Java Class for Sending HTML Form POST Request
Create a class named HttpClientFormPostExample
with the following code:
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.ContentType;
import java.util.ArrayList;
import java.util.List;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URLEncodedUtils;
public class HttpClientFormPostExample {
public static void main(String[] args) {
String url = "https://jsonplaceholder.typicode.com/posts";
// Create HttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create HttpPost request
HttpPost request = new HttpPost(url);
// Set form data
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("title", "foo"));
params.add(new BasicNameValuePair("body", "bar"));
params.add(new BasicNameValuePair("userId", "1"));
String form = URLEncodedUtils.format(params, "UTF-8");
StringEntity entity = new StringEntity(form, ContentType.APPLICATION_FORM_URLENCODED);
request.setEntity(entity);
// Set headers
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/x-www-form-urlencoded");
// Execute the request
try (CloseableHttpResponse response = httpClient.execute(request)) {
// Get HttpResponse Status
System.out.println("Response Code: " + response.getCode());
// Get HttpResponse Content
String content = EntityUtils.toString(response.getEntity());
System.out.println("Response Content: \n" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation
Adding Maven Dependencies:
- The
org.apache.httpcomponents.client5:httpclient5
dependency provides the classes needed to create and execute HTTP requests using Apache HttpClient.
- The
Creating HttpClient:
CloseableHttpClient httpClient = HttpClients.createDefault();
creates an instance ofCloseableHttpClient
using the default configuration.
Creating HttpPost Request:
HttpPost request = new HttpPost(url);
creates anHttpPost
request for the specified URL.
Setting Form Data:
- Create a list of
NameValuePair
objects representing the form data fields. - Use
URLEncodedUtils.format(params, "UTF-8");
to encode the form data as a URL-encoded string. StringEntity entity = new StringEntity(form, ContentType.APPLICATION_FORM_URLENCODED);
creates aStringEntity
with the form data and sets the content type toapplication/x-www-form-urlencoded
.request.setEntity(entity);
sets the entity (payload) for the POST request.
- Create a list of
Setting Headers:
request.setHeader("Accept", "application/json");
sets theAccept
header toapplication/json
.request.setHeader("Content-type", "application/x-www-form-urlencoded");
sets theContent-type
header toapplication/x-www-form-urlencoded
.
Executing the Request:
try (CloseableHttpResponse response = httpClient.execute(request)) { ... }
executes the POST request and retrieves the response.
Getting HttpResponse Status:
System.out.println("Response Code: " + response.getCode());
prints the status code of the HTTP response.
Getting HttpResponse Content:
String content = EntityUtils.toString(response.getEntity());
converts the response entity to a string and prints the content.
Running the Example
To run the example, simply execute the HttpClientFormPostExample
class. You should see the status code and the response content printed in the console.
Example Output
Response Code: 201
Response Content:
{
"title": "foo",
"body": "bar",
"userId": "1",
"id": 101
}
Additional Configuration
Setting Custom Headers
You can set custom headers for the POST request by using the setHeader
method on the HttpPost
object.
request.setHeader("User-Agent", "Mozilla/5.0");
Handling Redirects
By default, Apache HttpClient handles redirects automatically. You can customize this behavior by using a custom HttpClientBuilder
.
CloseableHttpClient httpClient = HttpClients.custom()
.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(String method) {
return true;
}
})
.build();
Setting Timeouts
You can set connection and socket timeouts by using RequestConfig
.
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
HttpPost request = new HttpPost(url);
request.setConfig(requestConfig);
Conclusion
Using Apache HttpClient to make an HTML form POST request is straightforward and flexible. By following this tutorial, you should now be able to create and execute POST requests with form data, handle responses, and customize various aspects of the HTTP request and response process. Apache HttpClient provides a comprehensive set of features that make it an excellent choice for handling HTTP operations in Java applications. The JSONPlaceholder API serves as a practical and convenient source for testing and prototyping your HTTP requests.
Comments
Post a Comment
Leave Comment