httpurlconnection发送post
时间: 2023-04-28 10:06:12 浏览: 66
使用HttpURLConnection发送POST请求需要以下步骤:
1. 创建URL对象
2. 打开连接
3. 设置请求方式为POST
4. 设置请求属性
5. 发送请求数据
6. 获取响应结果
7. 关闭连接
示例代码:
```java
// 创建URL对象
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方式为POST
connection.setRequestMethod("POST");
// 设置请求属性
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
// 发送请求数据
OutputStream outputStream = connection.getOutputStream();
outputStream.write("key1=value1&key2=value2".getBytes());
outputStream.flush();
outputStream.close();
// 获取响应结果
int responseCode = connection.getResponseCode();
InputStream inputStream = connection.getInputStream();
// 关闭连接
connection.disconnect();
```
这是一个简单的POST请求示例,你可能需要根据需要进行更改。