在Java中發(fā)送GET請(qǐng)求并傳遞header參數(shù),可以使用java.net.HttpURLConnection
類(lèi)。下面是一個(gè)示例代碼:
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 {
// 創(chuàng)建URL對(duì)象
URL url = new URL("http://example.com/api?param1=value1¶m2=value2");
// 打開(kāi)連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設(shè)置請(qǐng)求方法為GET
connection.setRequestMethod("GET");
// 設(shè)置header參數(shù)
connection.setRequestProperty("Header1", "Value1");
connection.setRequestProperty("Header2", "Value2");
// 獲取響應(yīng)代碼
int responseCode = connection.getResponseCode();
// 讀取響應(yīng)內(nèi)容
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
// 打印響應(yīng)內(nèi)容
System.out.println(response.toString());
// 關(guān)閉連接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上述代碼中,通過(guò)setRequestProperty
方法設(shè)置了header參數(shù),然后通過(guò)getInputStream
方法獲取響應(yīng)內(nèi)容。注意,需要將http://example.com/api?param1=value1¶m2=value2
替換為實(shí)際的請(qǐng)求URL,并根據(jù)需要設(shè)置自定義的header參數(shù)。