import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetRequestExample {
private static final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
// 目标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", USER_AGENT);
// 获取响应码
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());
}
}
java.io和java.net中的相关类来处理HTTP请求。User-Agent头部信息。URL对象。openConnection()方法打开与目标URL的连接,并将其转换为HttpURLConnection对象。setRequestMethod("GET")指定这是一个GET请求。getResponseCode()获取服务器的响应状态码。BufferedReader读取服务器返回的内容,并将其存储在StringBuffer中。这段代码展示了如何使用Java发送一个简单的GET请求并处理服务器的响应。
上一篇:java多线程并发执行
下一篇:java换行
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站