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