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

How to Send HTTP POST Requests in Java Using HttpURLConnection?

Patricia Arquette
Release: 2024-12-30 10:01:16
Original
311 people have browsed it

How to Send HTTP POST Requests in Java Using HttpURLConnection?

Sending HTTP Requests in Java

HTTP requests are fundamental to web development, allowing clients to communicate with servers. In Java, sending an HTTP request involves utilizing the java.net.HttpUrlConnection class.

The following code snippet demonstrates how to construct and send an HTTP POST request:

public static String executePost(String targetURL, String urlParameters) {
  HttpURLConnection connection = null;

  try {
    URL url = new URL(targetURL);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");
    connection.setUseCaches(false);
    connection.setDoOutput(true);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();

    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
      response.append(line).append('\r');
    }
    rd.close();
    return response.toString();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}
Copy after login

This code creates a connection to the specified URL, sets the request method to POST, and adds necessary headers. It then writes the request parameters to the output stream and sends the request. The server's response is retrieved from the input stream and returned as a string.

The above is the detailed content of How to Send HTTP POST Requests in Java Using HttpURLConnection?. 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