java post表单
时间: 2023-11-07 13:54:51 浏览: 44
在 Java 中,可以使用 HttpURLConnection 类发送 POST 请求提交表单数据,具体步骤如下:
1. 创建 URL 对象,并设置请求的 URL 地址。
```
URL url = new URL("https://example.com/submit");
```
2. 打开 URL 连接,并设置请求方法为 POST。
```
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
```
3. 设置请求头信息,包括 Content-Type 和 Content-Length。
```
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(formData.length()));
```
4. 向连接中写入表单数据。
```
OutputStream os = con.getOutputStream();
os.write(formData.getBytes());
```
5. 发送请求并获取响应。
```
int responseCode = con.getResponseCode();
InputStream is = con.getInputStream();
```
完整示例代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class PostFormExample {
public static void main(String[] args) throws IOException {
// 表单数据
String formData = "name=John&age=30";
// 创建 URL 对象
URL url = new URL("https://example.com/submit");
// 打开 URL 连接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
con.setRequestMethod("POST");
// 设置请求头信息
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(formData.length()));
// 向连接中写入表单数据
OutputStream os = con.getOutputStream();
os.write(formData.getBytes(StandardCharsets.UTF_8));
// 发送请求并获取响应
int responseCode = con.getResponseCode();
InputStream is = con.getInputStream();
// 处理响应数据
// ...
}
}
```