Java通过HttpClient实现请求接口发送文件
引入POM:
<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>
代码实现:
public void httpPostFile(String url, MultipartFile file) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); String filename = file.getOriginalFilename(); builder.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, filename); // 如果需要,传递额外参数 // StringBody fileName = new StringBody("文件名称", ContentType.MULTIPART_FORM_DATA); // StringBody userName = new StringBody("用户名", ContentType.MULTIPART_FORM_DATA); // builder.addPart("fileName", fileName); // builder.addPart("userName", userName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } }