java 使用HttpClient发送post请求,参数包括MultipartFile、Map以及File转MockMultipartFile
遇到使用java调用其他系统的http接口时,发送的参数中有文件,不太好处理,如下总结了发送带文件的的http方法,发送的文件还需要先将File 转成MockMultipartFile 否则接收会报错。
关键的代码和依赖如下所示。
一、依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- File转MultipartFile使用 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.8.RELEASE</version>
<scope>compile</scope>
</dependency>
二、File转MockMultipartFile
File file = new File("d://1//test.png");
try {
// 创建 FileInputStream
FileInputStream input = new FileInputStream(file);
// 使用 MockMultipartFile 初始化 MultipartFile
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "audio/mpeg", input);
httpUtil.sendPostRequest("http://×××××××/add", multipartFile, formData);
} catch (Exception e) {
e.printStackTrace();
}
三、http的发送方法
public static void sendPostRequest(String url, MultipartFile multipartFile, Map<String, String> formData) throws IOException {
// Create an instance of CloseableHttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create a HttpPost object and set the URL
HttpPost post = new HttpPost(url);
// Create a MultipartEntityBuilder to build the multipart form data
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// Add form data fields to the builder
for (Map.Entry<String, String> entry : formData.entrySet()) {
builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", StandardCharsets.UTF_8));
}
// Add the file part to the builder
builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, multipartFile.getOriginalFilename());
// Build the HttpEntity and set it to the HttpPost object
HttpEntity entity = builder.build();
post.setEntity(entity);
// Execute the request and get the response
try (CloseableHttpResponse response = httpClient.execute(post)) {
// Process the response
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseString = EntityUtils.toString(responseEntity);
System.out.println("Response: " + responseString);
}
}
}
}
浙公网安备 33010602011771号