规范的写法
需要的依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
代码
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("path/to/your/file.txt"), ContentType.DEFAULT_BINARY, "file.txt"); // 传输文件
builder.addTextBody("param1", "value1"); // 传输文本
builder.addTextBody("param2", "value2");
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpPost);
// 处理响应...
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String inputLine;
StringBuilder responseStr = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
responseStr.append(inputLine);
}
in.close();
System.out.println("==@@" + responseStr.toString());
content.close();
不规范的写法
public static String sendMultipartFormDataPostRequest(String urlString, String data) throws IOException {
String fullUrl = urlString + "?" + data;
log.info("完整请求路径为{}", fullUrl);
URL url = new URL(fullUrl);
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 允许输入输出流
connection.setDoInput(true);
connection.setDoOutput(true);
// 设置请求头信息
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
// 创建请求体输出流
// OutputStream outputStream = connection.getOutputStream();
// PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
// 添加请求体结束边界
// writer.flush();
// 关闭流
// writer.close();
// outputStream.close();
// 发送请求并获取响应
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
// 输出响应结果
log.info("Response Code: {} Response Message: {}" , responseCode, responseMessage);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (Exception e) {
throw e;
} finally {
// 关闭连接
if (connection != null) {
connection.disconnect();
}
}
}
数据可以和get请求一样用&分隔key=value的形式拼接到地址后面