在Java中發送GET請求并傳遞header參數,可以使用java.net.HttpURLConnection
類。下面是一個示例代碼:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// 創建URL對象
URL url = new URL("http://example.com/api?param1=value1¶m2=value2");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法為GET
connection.setRequestMethod("GET");
// 設置header參數
connection.setRequestProperty("Header1", "Value1");
connection.setRequestProperty("Header2", "Value2");
// 獲取響應代碼
int responseCode = connection.getResponseCode();
// 讀取響應內容
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
// 打印響應內容
System.out.println(response.toString());
// 關閉連接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上述代碼中,通過setRequestProperty
方法設置了header參數,然后通過getInputStream
方法獲取響應內容。注意,需要將http://example.com/api?param1=value1¶m2=value2
替換為實際的請求URL,并根據需要設置自定義的header參數。