import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
// 创建URL对象,指定要访问的HTTP地址
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 如果响应码是200,表示请求成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
// 关闭输入流
in.close();
// 输出响应内容
System.out.println("Response Content: " + content.toString());
} else {
System.out.println("GET request failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
URL类指定要访问的HTTP地址。openConnection()方法打开一个到该URL的连接,并将其转换为HttpURLConnection对象。setRequestMethod("GET")将请求方法设置为GET。getResponseCode()获取服务器返回的HTTP状态码。BufferedReader读取服务器返回的内容。try-catch块捕获并处理可能发生的异常。上一篇:java stopwatch
下一篇:java解析xml
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站