HttpClient中转上传文件
原文:https://www.cnblogs.com/lyxy/p/5629151.html
場(chǎng)景:客戶(hù)端(瀏覽器)A---->選擇文件上傳---->服務(wù)器B---->中轉(zhuǎn)文件---->服務(wù)器C---->返回結(jié)果---->服務(wù)器B---->客戶(hù)端A
有時(shí)候在項(xiàng)目中需要把上傳的文件中轉(zhuǎn)到第三方服務(wù)器,第三方服務(wù)器提供一個(gè)接收文件的接口。
而我們又不想把文件先上傳到服務(wù)器保存后再通過(guò)File來(lái)讀取文件上傳到第三方服務(wù)器,我們可以使用HttpClient來(lái)實(shí)現(xiàn)。
因?yàn)轫?xiàng)目使用的是Spring+Mybatis框架,文件的上傳采用的是MultipartFile,而FileBody只支持File。
所以這里采用MultipartEntityBuilder的addBinaryBody方法以數(shù)據(jù)流的形式上傳。
這里需要引入兩個(gè)jar包:httpclient-4.4.jar和httpmime-4.4.jar
Maven pom.xml引入
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.4</version></dependency>上傳代碼:
Map<String, String> map = new HashMap<>(); CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; try {String fileName = file.getOriginalFilename();// 路徑自定義HttpPost httpPost = new HttpPost("http://192.168.xxx.xx:xxxx/api/**");
//此處可以設(shè)置請(qǐng)求頭
//httpPost.setHeader("Authrization",“自定義的token”)MultipartEntityBuilder builder = MultipartEntityBuilder.create();// 文件流builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 類(lèi)似瀏覽器表單提交,對(duì)應(yīng)input的name和valuebuilder.addTextBody("filename", fileName);HttpEntity entity = builder.build();httpPost.setEntity(entity);// 執(zhí)行提交HttpResponse response = httpClient.execute(httpPost);HttpEntity responseEntity = response.getEntity();if (responseEntity != null) {// 將響應(yīng)內(nèi)容轉(zhuǎn)換為字符串result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));// 將響應(yīng)內(nèi)容轉(zhuǎn)換成Map,JSON依賴(lài)為fastJsonMap resultMap= JSON.parseObject(result, Map.class);
// 封裝數(shù)據(jù)返回給前端
map.put("key",resultMap.get("field"));} } catch (Exception e) {e.printStackTrace(); } finally {try {httpClient.close();} catch (IOException e) {e.printStackTrace();} }
轉(zhuǎn)載于:https://www.cnblogs.com/joelan0927/p/10879312.html
總結(jié)
以上是生活随笔為你收集整理的HttpClient中转上传文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 企业网络建设拓扑
- 下一篇: 显示器尺寸对照表_电脑液晶屏尺寸如何计算