java中http请求代码实现
时间: 2024-10-23 17:18:32 浏览: 14
java http token请求代码实例
5星 · 资源好评率100%
在Java中,常见的HTTP请求通常通过`java.net.HttpURLConnection`或者第三方库如`Apache HttpClient`、`OkHttp`等来进行。这里我将以`HttpURLConnection`为例,展示如何发送GET请求的基本示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("https://api.example.com/data");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 设置用户代理
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 response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println(response.toString());
} else {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们首先创建一个`URL`对象,然后通过`openConnection()`获取到`HttpURLConnection`。设置请求方法为GET,并可以添加其他请求头。然后检查响应状态码,如果成功(200),就读取并打印服务器返回的数据。
阅读全文