Java http协议 post请求接口
时间: 2024-06-17 20:08:02 浏览: 20
Java中可以使用HttpURLConnection或者Apache HttpClient来发送HTTP请求。其中,HttpURLConnection是Java标准库中提供的类,它可以通过向服务器发送不同的HTTP请求方法(如GET、POST等)来实现与服务器的交互。Apache HttpClient是一个第三方库,相对于HttpURLConnection来说,它提供了更多的功能和更简洁的API接口。
下面以HttpURLConnection为例介绍如何发送POST请求:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostExample {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api/v1/user"; // 请求的url地址
String body = "{\"username\":\"test\",\"password\":\"123456\"}"; // 请求体
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // 设置请求方法为POST
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // 设置请求头
con.setDoOutput(true); // 允许输出流
// 发送请求体
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
wr.write(bodyBytes);
wr.flush();
}
// 处理响应结果
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());
}
}
}
```
以上代码演示了如何使用HttpURLConnection发送POST请求,其中`url`表示请求的url地址,`body`表示请求体,需要根据实际情况进行修改。在发送请求时,需要设置请求方法为POST,并设置请求头`Content-Type`为`application/json; charset=UTF-8`。在发送请求体后,可以通过`getResponseCode`方法获取响应状态码,通过`getInputStream`方法获取响应内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)