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.
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(); }
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!