java 转发上传文件_java 后台请求其他接口转发文件
发布日期:2021-06-24 16:15:16 浏览次数:4 分类:技术文章

本文共 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;

}

转载地址:https://blog.csdn.net/weixin_33758343/article/details/114153474 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java get set 同步_java – getResultSet()“每个结果只能调用一次”
下一篇:ice glacier2 java_ICE提纲之demo/Glacier2/callback(跨网回调)

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月04日 06时25分46秒