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:
To send the request:
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(); }
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!