java 中如何 发送http post请求
时间: 2023-11-12 22:07:13 浏览: 43
在 Java 中发送 HTTP POST 请求需要使用 Java 的 HttpURLConnection 类。下面是一个简单的示例:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class HttpPostExample {
public static void main(String[] args) throws IOException {
// 设置 POST 请求的 URL
URL url = new URL("http://example.com/api");
// 创建 HttpURLConnection 对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
connection.setRequestMethod("POST");
// 允许输出流
connection.setDoOutput(true);
// 设置请求体数据
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("key1=value1&key2=value2");
writer.flush();
writer.close();
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 获取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印响应数据
System.out.println("Response Data : " + response.toString());
}
}
```
在上面的示例中,我们首先创建了一个 URL 对象,然后使用 HttpURLConnection 类打开连接。接下来设置请求方法为 POST,允许输出流并设置请求体数据。然后我们可以获取响应码和响应数据,打印到控制台上。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)