java中如何发送post请求
时间: 2023-09-26 11:11:20 浏览: 55
可以使用HttpURLConnection或者HttpClient类库来发送POST请求。其中HttpURLConnection是Java标准库中的类,HttpClient则是Apache HTTP组件库中的类。具体实现可以参考以下代码:
使用HttpURLConnection发送POST请求:
```java
URL url = new URL("http://www.example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json");
OutputStream out = conn.getOutputStream();
String postData = "{\"name\": \"John\", \"age\": 30}";
out.write(postData.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = conn.getInputStream();
// 处理响应数据
in.close();
conn.disconnect();
```
使用HttpClient发送POST请求:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com/api");
httpPost.setHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity("{\"name\": \"John\", \"age\": 30}", "UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
// 处理响应数据
EntityUtils.consume(responseEntity);
response.close();
httpClient.close();
```
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)