import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) {
try {
// 创建URL对象,指定要请求的URL地址
URL url = new URL("http://example.com/api/data");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 设置请求头(可选)
connection.setRequestProperty("User-Agent", "Java HTTP GET Example");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 处理响应内容(这里简单地打印响应码)
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容(此处省略具体实现)
System.out.println("Request succeeded.");
} else {
System.out.println("Request failed.");
}
// 断开连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL类创建一个表示目标API地址的对象。openConnection()方法打开到该URL的连接,并将其转换为HttpURLConnection类型。setRequestMethod("GET")将请求方法设置为GET。setRequestProperty方法添加自定义的请求头,如User-Agent。getResponseCode()方法获取服务器返回的状态码。disconnect()方法关闭连接。上一篇:java switch enum
下一篇:java spark sql
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站