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

How to Send HTTP POST Requests Using Java?

Barbara Streisand
Release: 2024-12-22 16:37:11
Original
681 people have browsed it

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();
Copy after login

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");
    Copy after login

    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();
    Copy after login

    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());
    Copy after login

    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!

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