Sending HTTP Requests in Java
The ability to send HTTP requests is essential for interacting with remote servers and web APIs in Java. One way to compose and transmit HTTP requests is through the java.net.HttpUrlConnection class.
Creating the HTTP Request
To create an HTTP request, you can use the following steps:
Sending the HTTP Request
Once the request is formulated, you can send it to the server using a DataOutputStream:
Getting the HTTP Response
Upon sending the request, you can obtain the response from the server:
Example Code Snippet
The following Java code demonstrates how to send an HTTP POST request using the HttpUrlConnection class:
import java.net.HttpURLConnection; import java.net.URL; import java.io.DataOutputStream; import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class HttpPostExample { public static void main(String[] args) { String targetURL = "https://example.com/api/endpoint"; String urlParameters = "key1=value1&key2=value2"; 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.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); response.append('\r'); } rd.close(); System.out.println(response.toString()); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }
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!