// 示例代码:Java 中的 HTTP 请求示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
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";
// 发送 GET 请求并获取响应
String response = sendGet(url);
System.out.println("GET Response: " + response);
}
// 发送 GET 请求的方法
private static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求头信息
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "GET request failed.";
}
}
}
HttpURLConnection 用于发起 HTTP 请求,BufferedReader 和 InputStreamReader 用于读取响应内容。上一篇:java读取文件夹下的所有文件
下一篇:java循环语句
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站