在Java中實現GET請求可以使用HttpURLConnection類來實現。以下是一個簡單的示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequest {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的示例中,我們創建了一個URL對象,然后通過調用openConnection()
方法獲取HttpURLConnection對象。接著設置請求方法為GET,并發送請求。最后讀取響應內容并輸出到控制臺。