Home >Java >javaTutorial >How to Send HTTP POST Requests Using Java?

How to Send HTTP POST Requests Using Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-22 16:37:11722browse

How to Send HTTP POST Requests Using Java?

Sending HTTP POST Requests with Java

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:

  1. 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.

  2. 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."

  3. 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!

Statement:
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