HttpClient中转上传文件

原文:https://www.cnblogs.com/lyxy/p/5629151.html

场景:客户端(浏览器)A---->选择文件上传---->服务器B---->中转文件---->服务器C---->返回结果---->服务器B---->客户端A

有时候在项目中需要把上传的文件中转到第三方服务器,第三方服务器提供一个接收文件的接口。

而我们又不想把文件先上传到服务器保存后再通过File来读取文件上传到第三方服务器,我们可以使用HttpClient来实现。

因为项目使用的是Spring+Mybatis框架,文件的上传采用的是MultipartFile,而FileBody只支持File。

所以这里采用MultipartEntityBuilder的addBinaryBody方法以数据流的形式上传。

这里需要引入两个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/**");      
//此处可以设置请求头       
//httpPost.setHeader("Authrization",“自定义的token”) MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 文件流 builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName); // 类似浏览器表单提交,对应input的name和value builder.addTextBody("filename", fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 执行提交 HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 将响应内容转换为字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); // 将响应内容转换成Map,JSON依赖为fastJson Map resultMap= JSON.parseObject(result, Map.class);
// 封装数据返回给前端         
map.put("key",resultMap.get("field")); } } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } }

  

原文地址:https://www.cnblogs.com/joelan0927/p/10879312.html