Home > Java > javaTutorial > How to Compose and Send HTTP Requests in Java using HttpUrlConnection?

How to Compose and Send HTTP Requests in Java using HttpUrlConnection?

Barbara Streisand
Release: 2024-12-30 11:16:09
Original
237 people have browsed it

How to Compose and Send HTTP Requests in Java using HttpUrlConnection?

HTTP Request Composition in Java

In Java, composing and sending an HTTP request involves utilizing the java.net.HttpUrlConnection class.

To construct an HTTP request, follow these steps:

  • Establish a Connection: Create a URL object representing the target web server and establish an HttpURLConnection instance.
  • Configure Headers: Set HTTP headers such as "Content-Type" and "Content-Length" to specify the request's content type and length.
  • Enable Output: Set the setDoOutput property to true to allow output to the connection.

To send the request:

  • Write Request: Use a DataOutputStream to write the request parameters to the connection's output stream.
  • Get Response: Retrieve the server's response by opening an InputStream from the connection and reading the response line by line.

Here's an example of sending a POST request using HttpUrlConnection:

public static String executePost(String targetURL, String urlParameters) {
  // Create connection and set headers
  HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection();
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));

  // Enable output and write request
  connection.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.close();

  // Get response
  BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  StringBuilder response = new StringBuilder();
  String line;
  while ((line = rd.readLine()) != null) {
    response.append(line);
    response.append('\r');
  }
  rd.close();

  return response.toString();
}
Copy after login

The above is the detailed content of How to Compose and Send HTTP 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