帮忙使用java写个http发送请求的demo
时间: 2024-03-25 22:38:15 浏览: 15
好的,以下是使用Java发送HTTP请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDemo {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api");
// 创建HTTP连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 设置请求头参数
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer xxxxxxxx");
// 发送请求
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应内容
System.out.println(responseCode);
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请将URL和请求头参数替换为您要访问的API的实际值。