JAVA调用POST请求接口传递文件
一、引入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.3</version>
</dependency>
二、代码实现
private Long uploadFile(File file) {
String authorization = crmTokenUtil.getAuthorization();
String responseJsonString = "";
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fileInputStream.read(buffer);
fileInputStream.close();
InputStream inputStream = new ByteArrayInputStream(buffer);
HttpPost httpPost = new HttpPost(requestUrl);
httpPost.setHeader("Authorization", authorization);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
// 把文件加到HTTP的post请求中
builder.addBinaryBody("files", inputStream, ContentType.MULTIPART_FORM_DATA, file.getName());
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
responseJsonString = EntityUtils.toString(responseEntity, "UTF-8");
log.info("调用上传文件接口返回结果===>>" + responseJsonString);
} catch (Exception e) {
log.error("调用上传文件接口失败===>>" + e.getMessage());
throw new CostAccountingException("调用上传文件接口失败" + e.getMessage());
} finally {
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
log.info("调用上传文件接口失败===>>" + e.getMessage());
throw new CostAccountingException("调用上传文件接口失败" + e.getMessage());
}
}
}

浙公网安备 33010602011771号