用JAVA代码实现HTTP GET
时间: 2024-12-02 22:17:01 浏览: 10
在Java中,我们可以使用HttpURLConnection或者更现代的HttpClient库来发送HTTP GET请求。以下是使用HttpURLConnection的一个简单示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api/resource");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 设置请求方法为GET
// 添加请求头,如需要身份验证
connection.setRequestProperty("Authorization", "Bearer your_token");
connection.setRequestProperty("Accept", "application/json"); // 设置接受内容类型
// 连接并获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // 确保请求成功
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
// 输出响应数据
System.out.println(content.toString());
} else {
System.out.println("Request failed with status code " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文