共計 1141 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中發(fā)送 GET 請求并傳遞 header 參數(shù),可以使用 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 {// 創(chuàng)建 URL 對象
URL url = new URL("http://example.com/api?param1=value1¶m2=value2");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法為 GET
connection.setRequestMethod("GET");
// 設置 header 參數(shù)
connection.setRequestProperty("Header1", "Value1");
connection.setRequestProperty("Header2", "Value2");
// 獲取響應代碼
int responseCode = connection.getResponseCode();
// 讀取響應內(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();
// 打印響應內(nèi)容
System.out.println(response.toString());
// 關閉連接
connection.disconnect();} catch (Exception e) {e.printStackTrace();
}
}
}
在上述代碼中,通過 setRequestProperty
方法設置了 header 參數(shù),然后通過 getInputStream
方法獲取響應內(nèi)容。注意,需要將 http://example.com/api?param1=value1¶m2=value2
替換為實際的請求 URL,并根據(jù)需要設置自定義的 header 參數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2023-12-13