Home > Java > javaTutorial > How to Send a POST Request with Parameters in Java Using Apache HttpClient?

How to Send a POST Request with Parameters in Java Using Apache HttpClient?

Susan Sarandon
Release: 2024-12-22 03:53:10
Original
462 people have browsed it

How to Send a POST Request with Parameters in Java Using Apache HttpClient?

Sending HTTP POST Request In Java

The goal is to send data (id = 10) to a remote server using the POST method. The Java code provided attempts to open a connection to the remote URL, but fails to specify the POST request parameters.

Solution Using Apache HttpClient

Apache HttpClient is a popular Java library for sending and receiving HTTP requests. Here's how to achieve POST functionality in Java using it:

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.example.com/page.php");

// Request parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "10"));

// Set request parameters encoded in UTF-8 as POST body
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

// Execute the HTTP POST request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

// Handle response
if (entity != null) {
    // Process response body, e.g., print the HTML content
    InputStream instream = entity.getContent();
}
Copy after login

In this updated solution, the deprecated classes from the older Apache HTTP Components version have been replaced with their newer equivalents.

The above is the detailed content of How to Send a POST Request with Parameters in Java Using Apache HttpClient?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template