Home >Java >javaTutorial >How to Send HTTP Requests in Java Using `HttpUrlConnection`?
Composing and Sending HTTP Requests in Java
To harness the power of HTTP requests in Java, you can utilize the java.net.HttpUrlConnection class. It provides a comprehensive API for creating and dispatching HTTP requests to any web server.
Creating the Connection
To establish the connection, you'll create a URL object and use it to establish an HttpUrlConnection connection. Specify the request method (e.g., POST, GET) and set necessary headers, such as Content-Type and Content-Length.
Preparing the HTTP Request
For a POST request, format the request parameters as a query string (e.g., "name=John&age=30"). Use DataOutputStream to write the parameters to the output stream.
Sending the Request
Once the request is ready, send it by using DataOutputStream.writeBytes() to transmit the request body. The web server will respond with the requested resource.
Receiving the Response
InputStream is used to retrieve the response from the server. Use BufferedReader to read the response line by line and construct the final response body.
Sample Code
Here's a code snippet that showcases how to execute an HTTP POST request using the aforementioned techniques:
import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.io.OutputStreamWriter; import java.io.IOException; public static void sendHttpRequest() throws IOException { // Create the connection URL url = new URL("http://example.com/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Build the request parameters String postData = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode("John", "UTF-8"); // Send the request OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(postData); writer.flush(); // Get the response int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } connection.disconnect(); }
By following these steps and utilizing the HttpUrlConnection class, you can effortlessly compose and transmit HTTP requests in your Java applications.
The above is the detailed content of How to Send HTTP Requests in Java Using `HttpUrlConnection`?. For more information, please follow other related articles on the PHP Chinese website!