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());
				}
			}
		}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM