import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
private static final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
// 发送GET请求
sendGet();
}
// 发送GET请求的方法
private static void sendGet() throws Exception {
String url = "http://www.example.com"; // 请求的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("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();
// 打印结果
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
}
}
java.net.HttpURLConnection和java.net.URL等类,用于发起HTTP请求。setRequestProperty方法设置了User-Agent,模拟浏览器发送请求。HttpURLConnection对象发送GET请求,并获取响应码。这段代码展示了如何使用Java发送一个简单的HTTP GET请求并处理响应。
上一篇:java 字符串转数组
下一篇:java面向对象的三大特性
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站