要使用Java發送HTTP請求并獲取URL響應,可以使用java.net.HttpURLConnection
類
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
public static void main(String[] args) {
try {
// 創建URL對象
URL url = new URL("https://api.example.com/data");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法(GET或POST)
connection.setRequestMethod("GET");
// 設置請求頭(可選)
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 獲取響應碼
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應內容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
// 關閉輸入流
in.close();
// 輸出響應內容
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
這個示例向https://api.example.com/data
發送一個GET請求,然后讀取并輸出響應內容。你可以根據需要修改URL、請求方法和請求頭。如果你需要發送POST請求并提交數據,可以使用connection.setDoOutput(true)
和connection.getOutputStream()
方法。