java通过不同请求转发不同端口_java 后台请求其他接口转发文件

该博客介绍了如何在Java中使用HttpClient库来转发文件到不同的API端口。主要方法是创建HttpPost对象,设置请求头,构建MultipartEntity并添加文件及额外参数,最后执行HTTP请求获取响应。
摘要由CSDN通过智能技术生成

/*** 使用httpclint 发送文件

*@paramurl: 接口全路径

*@paramfile: 上传文件

*@paramfileParamName: 接口对应文件的参数名:相当于@RequestParam("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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值