java调用http接口post请求
时间: 2023-11-20 08:05:43 浏览: 109
Http.zip_java http post
可以使用Java自带的HttpURLConnection类来发送POST请求,以下是示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api"; // 请求的URL地址
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头部信息
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", "Java client");
// 设置请求体内容
String requestBody = "{\"key\":\"value\"}";
byte[] requestBodyBytes = requestBody.getBytes(StandardCharsets.UTF_8);
// 发送POST请求
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
os.write(requestBodyBytes, 0, requestBodyBytes.length);
}
// 获取响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应内容
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println("Response Body : " + response.toString());
}
}
}
```
需要替换以下部分来适配你的请求:
- 将`url`变量的值替换为实际请求的URL地址。
- 将`Content-Type`请求头和请求体的内容替换为实际的值。
阅读全文