Q3
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
String url = "https://api.example.com/data";
try {
// 创建 URL 对象
URL obj = new URL(url);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 设置请求头
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept", "application/json");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
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 Body: " + response.toString());
} else {
System.err.println("GET request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}