博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 转发上传文件_java 后台请求其他接口转发文件
阅读量:1543 次
发布时间:2019-04-21

本文共 1498 字,大约阅读时间需要 4 分钟。

/*** 使用httpclint 发送文件

*@paramurl: 接口全路径

*@paramfile: 上传文件

*@paramfileParamName: 接口对应文件的参数名:[email protected]("fileParamName")

*@paramheaderParams: 请求头信息: 可能需要携带token,注意不要设置content-type

*@paramotherParams: 其他参数

*@return

*/

public static String uploadApiFile(String url ,MultipartFile file,String fileParamName,MapheaderParams,MapotherParams) {

CloseableHttpClient httpClient=HttpClients.createDefault();

String result= "";try{

String fileName=file.getOriginalFilename();

HttpPost httpPost= newHttpPost(url);//添加header

for (Map.Entrye : headerParams.entrySet()) {

httpPost.addHeader(e.getKey(), e.getValue());

}

MultipartEntityBuilder builder=MultipartEntityBuilder.create();

builder.setCharset(Charset.forName("utf-8"));

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题

builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);//文件流

for (Map.Entrye : otherParams.entrySet()) {

builder.addTextBody(e.getKey(), e.getValue());//类似浏览器表单提交,对应input的name和value

}

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"));

}

}catch(IOException e) {

e.printStackTrace();

}catch(Exception e) {

e.printStackTrace();

}finally{try{

httpClient.close();

}catch(IOException e) {

e.printStackTrace();

}

}returnresult;

}

转载地址:http://ehrdy.baihongyu.com/

你可能感兴趣的文章
IMU中加速度计、陀螺仪、磁力计的工作原理
查看>>
PCB上三防漆规范和注意事项
查看>>
进程和线程常见的19个问题
查看>>
Keil MDK 和 IAR EARM发展历程及历史版本下载
查看>>
精选汇总 | 嵌入式软件基础知识
查看>>
为什么大家都看好RISC-V
查看>>
Keil MDK利用 fromelf 实现axf 转 bin 的方法
查看>>
2.10. Wi-Fi
查看>>
Golang Ruby ASP PowerShell
查看>>
6.1. 信息收集 - Windows
查看>>
6.2. 持久化 - Windows
查看>>
6.3. 域渗透
查看>>
6.6. 痕迹清理
查看>>
6.7. 综合技巧
查看>>
7.1. 团队建设
查看>>
7.2. 安全开发
查看>>
7.4. ATT&CK
查看>>
7.6. 防御框架
查看>>
7.7. 加固检查
查看>>
技术文章系列分享朋友服务器惨遭挖矿的应急笔记
查看>>