如何用java发请求 post传参body form-data
时间: 2025-06-15 21:21:33 浏览: 21
在Java中,使用`HttpURLConnection`或基于Java的HTTP客户端库(例如`Apache HttpClient`、`RestAssured` 或 `Spring Framework`)发送POST请求并传递表单数据(Form Data),你需要按照以下步骤操作:
1. **使用`HttpURLConnection`**:
```java
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FormDataExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/endpoint";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置POST请求
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 添加表单数据到请求体
String formData = "key=value&another_key=another_value";
con.setDoOutput(true); // 开启输出流
try(OutputStream os = con.getOutputStream()) {
byte[] formDataBytes = formData.getBytes("UTF-8");
os.write(formDataBytes);
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("Response: " + readResponse(con));
}
}
private static String readResponse(HttpURLConnection connection) throws IOException {
StringBuilder result = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
return result.toString();
}
}
```
2. **使用`Apache HttpClient`**:
```java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpClientFormDataExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
// 添加表单数据
httpPost.setEntity(new StringEntity("key=value&another_key=another_value", "UTF-8"));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(httpPost);
// ...处理响应...
}
}
```
阅读全文
相关推荐


















