java提交post请求form-data
时间: 2024-11-12 12:36:39 浏览: 28
在Java中,如果你需要提交POST请求并携带表单数据(通常用于发送HTML表单),你可以使用`HttpURLConnection`或者第三方库如`Apache HttpClient`或`OkHttp`。这里我将演示如何使用`HttpURLConnection`。
```java
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostFormDataExample {
private static final String URL = "http://example.com/api"; // 替换为你实际的URL
public static void main(String[] args) throws Exception {
URL url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置POST请求
connection.setRequestMethod("POST");
connection.setDoOutput(true); // 表示有输出流,用于发送数据
// 添加表单数据,假设有个名为"name"的字段
String formContent = "name=John Doe&age=30";
byte[] formDataBytes = formContent.getBytes(); // 字符串转字节数组
// 写入OutputStream
try(OutputStream os = connection.getOutputStream()) {
os.write(formDataBytes);
}
// 获取响应状态码
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 关闭连接
connection.disconnect();
}
}
```
阅读全文