在Java中,要打印HTTP請求報文,你可以使用Java的網絡編程庫,例如java.net.HttpURLConnection
。以下是一個簡單的示例,展示了如何使用HttpURLConnection
發送GET請求并打印請求報文:
import java.io.BufferedReader;
import java.io.IOException;
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();
// 設置請求方法
connection.setRequestMethod("GET");
// 設置請求頭
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 打印請求報文
System.out.println("Request Method: " + connection.getRequestMethod());
System.out.println("Request URL: " + connection.getURL());
System.out.println("Request Headers: ");
for (String header : connection.getRequestProperties().keySet()) {
System.out.println(header + ": " + connection.getRequestProperty(header));
}
// 獲取響應狀態碼
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 Content: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
這個示例向https://api.example.com/data
發送一個GET請求,并打印請求報文。請注意,這個示例僅適用于簡單的GET請求。對于更復雜的請求(如POST請求、包含請求體的請求等),你需要根據需要調整代碼。