URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection();
With the code you provided, you have successfully created a connection to the target URL. However, to send data via the POST method, you need to perform the following steps:
Set the Request Method to POST:
ccc.setDoOutput(true); ccc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
By setting setDoOutput to true, you indicate that you intend to send data in the request. setRequestProperty sets the appropriate content type header for an HTTP POST form request.
Write the Data:
OutputStreamWriter out = new OutputStreamWriter(ccc.getOutputStream()); out.write("id=10"); out.flush();
Create an OutputStreamWriter to write the data to the connection's output stream. The data should be in the format of "name=value" pairs, separated by ampersands (&). In this example, we're sending the "id" parameter with the value "10."
Get the Response:
InputStreamReader in = new InputStreamReader(ccc.getInputStream());
After sending the data, you can obtain the server's response by creating an InputStreamReader to read from the connection's input stream.
By following these steps, you can successfully send HTTP POST requests with Java. Apache HttpClient, as mentioned in the updated answer, provides a convenient library for handling HTTP requests, but it's not necessary for this simple scenario.
The above is the detailed content of How to Send HTTP POST Requests Using Java?. For more information, please follow other related articles on the PHP Chinese website!