一、引入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());
}
}
}
