java 调用http post请求
时间: 2024-10-14 08:17:58 浏览: 34
在Java中,你可以使用多种库来发送HTTP POST请求,其中最常用的是`java.net.HttpURLConnection`或者第三方库如`Apache HttpClient`、`OkHttp`等。这里我们提供一个简单的示例,使用`HttpURLConnection`:
```java
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public classHttpPostExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api/endpoint"; // 替换为你实际的URL
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// 设置POST请求
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 发送数据(这里以JSON为例)
String jsonData = "{\"key\":\"value\"}"; // JSON字符串,替换为你的实际数据
OutputStream os = connection.getOutputStream();
os.write(jsonData.getBytes());
os.flush();
os.close();
// 读取响应
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (InputStreamReader reader = new InputStreamReader(connection.getInputStream())) {
System.out.println(reader.readLine());
}
} else {
System.err.println("Error: " + responseCode);
}
// 关闭连接
connection.disconnect();
}
}
```
阅读全文