怎么通过 HttpURLConnection 发送post请求,并以form-data的形式携带2个参?
时间: 2024-05-14 20:13:42 浏览: 75
可以通过以下代码实现:
```
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
String boundary = "---------------------------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream out = con.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true);
// 添加参数
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"param1\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
writer.append("\r\n");
writer.append("value1").append("\r\n");
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"param2\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
writer.append("\r\n");
writer.append("value2").append("\r\n");
// 添加文件
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"example.txt\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
writer.append("\r\n");
Files.copy(Paths.get("/path/to/example.txt"), out);
writer.append("\r\n");
// 结束标记
writer.append("--" + boundary + "--").append("\r\n");
writer.flush();
// 发送请求并读取响应
int responseCode = con.getResponseCode();
InputStream inputStream = responseCode < 400 ? con.getInputStream() : con.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
```
阅读全文