上传图片流

/**
* 使用httpclint 发送文件,如果不传输文件,直接设置fileParams=null,
* 如果不设置请求头参数,直接设置headerParams=null,就可以进行普通参数的POST请求了
*
* @param url 请求路径
* @param fileParams 文件参数
* @param otherParams 其他字符串参数
* @param headerParams 请求头参数
* @return 返回结果
*/
public static String uploadFile(String url, Map<String, MultipartFile> fileParams, Map<String, String> otherParams, Map<String, String> headerParams) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = “”;
try {
HttpPost httpPost = new HttpPost(url);
//设置请求头
if (headerParams != null && headerParams.size() > 0) {
for (Map.Entry<String, String> e : headerParams.entrySet()) {
String value = e.getValue();
String key = e.getKey();
if (StringUtils.isNotBlank(value)) {
httpPost.setHeader(key, value);
}
}
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
//加上此行代码解决返回中文乱码问题
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//文件传输http请求头(multipart/form-data)
if (fileParams != null && fileParams.size() > 0) {
for (Map.Entry<String, MultipartFile> e : fileParams.entrySet()) {
String fileParamName = e.getKey();
MultipartFile file = e.getValue();
if (file != null) {
String fileName = file.getOriginalFilename();
// 文件流
builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
}
}
}
//字节传输http请求头(application/json)
ContentType contentType = ContentType.create(“application/json”, StandardCharsets.UTF_8);
if (otherParams != null && otherParams.size() > 0) {
for (Map.Entry<String, String> e : otherParams.entrySet()) {
String value = e.getValue();
if (StringUtils.isNotBlank(value)) {
// 类似浏览器表单提交,对应input的name和value
builder.addTextBody(e.getKey(), value, contentType);
}
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值