java使用post发送http请求
时间: 2023-04-24 10:01:51 浏览: 77
Java可以使用HttpURLConnection类来发送POST请求,具体步骤如下:
1. 创建URL对象,指定要访问的URL地址。
2. 调用URL对象的openConnection()方法,返回一个URLConnection对象。
3. 将URLConnection对象强制转换为HttpURLConnection对象。
4. 设置请求方法为POST,调用setRequestMethod()方法。
5. 设置请求头信息,调用setRequestProperty()方法。
6. 设置请求体信息,调用getOutputStream()方法获取输出流,将请求参数写入输出流。
7. 发送请求,调用getInputStream()方法获取输入流,读取服务器返回的数据。
8. 关闭输入流和输出流,断开连接。
示例代码如下:
```
import java.io.*;
import java.net.*;
public class HttpPost {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://www.example.com");
// 打开连接
URLConnection connection = url.openConnection();
// 强制转换为HttpURLConnection对象
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
// 设置请求方法为POST
httpURLConnection.setRequestMethod("POST");
// 设置请求头信息
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length()));
// 设置请求体信息
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
outputStream.close();
// 发送请求
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
inputStream.close();
// 断开连接
httpURLConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,data为请求参数,可以根据实际情况进行修改。