陕西住房和城乡建设网站,网站备案几天,易网网站,网站开发下载功能如何实现原文#xff1a;https://www.cnblogs.com/lyxy/p/5629151.html 场景#xff1a;客户端(浏览器)A----选择文件上传----服务器B----中转文件----服务器C----返回结果----服务器B----客户端A 有时候在项目中需要把上传的文件中转到第三方服务器https://www.cnblogs.com/lyxy/p/5629151.html 场景客户端(浏览器)A----选择文件上传----服务器B----中转文件----服务器C----返回结果----服务器B----客户端A 有时候在项目中需要把上传的文件中转到第三方服务器第三方服务器提供一个接收文件的接口。 而我们又不想把文件先上传到服务器保存后再通过File来读取文件上传到第三方服务器我们可以使用HttpClient来实现。 因为项目使用的是SpringMybatis框架文件的上传采用的是MultipartFile而FileBody只支持File。 所以这里采用MultipartEntityBuilder的addBinaryBody方法以数据流的形式上传。 这里需要引入两个jar包httpclient-4.4.jar和httpmime-4.4.jar Maven pom.xml引入 dependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpclient/artifactIdversion4.4/version/dependencydependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpmime/artifactIdversion4.4/version/dependency 上传代码 MapString, 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和valuebuilder.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依赖为fastJsonMap 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