import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetRequestExample {
public static void main(String[] args) {
try {
// 定义请求的URL
String url = "http://example.com/api/data";
// 创建URL对象
URL obj = new URL(url);
// 打开连接
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为GET
con.setRequestMethod("GET");
// 设置请求头(可选)
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 获取响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.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();
}
}
}
java.io.BufferedReader、java.io.InputStreamReader、java.net.HttpURLConnection和java.net.URL等类来处理HTTP请求。URL对象。openConnection()方法打开到该URL的连接,并将其转换为HttpURLConnection对象。setRequestMethod("GET")将请求方法设置为GET。setRequestProperty方法添加自定义的请求头,例如User-Agent。getResponseCode()方法获取服务器返回的HTTP状态码。getInputStream()方法读取服务器返回的数据,并使用BufferedReader逐行读取。try-catch块捕获并处理可能发生的异常。下一篇:java集合转换成字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站