Java通过http请求发送文件MultipartFile
写了一个工具类实现Java通过http请求发送文件,但其中遇到一些坑在这里标注一下
标注1
这里设置header的时候不能给header里的Content-Length赋值,否则会报错
Caused by: java.io.IOException: UT000036: Connection terminated parsing multipart data
标注2
此处的fileNameKey对应接收方controller处的@RequestParam(value = "file")里的名字,例如这里fileNameKey需要为file,否则接收方会报错
接收方controller示例:
@RequestMapping(value = "/upload")
public R upload(@RequestParam(value = "file") MultipartFile file) {
// xxx逻辑
}
工具类demo
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HttpFileUtil {
/**
* 以post方式调用第三方接口,以form-data 形式 发送 MultipartFile 文件数据
*
* @param url post请求url
* @param multipartFile 文件
* @param paramMap 表单里其他参数
* @return
*/
public static String doPostFormData(String url, MultipartFile multipartFile, Map paramMap, Header header, String fileNameKey) {
// 创建Http实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 请求参数配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(30000).build();
httpPost.setConfig(requestConfig);
/** 标注1.这里设置header的时候不能给header里的Content-Length赋值,否则会报错 */
// 请求header
httpPost.addHeader(header);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// builder.setMode(HttpMultipartMode.RFC6532);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
String fileName = multipartFile.getOriginalFilename();
/** 标注2:此处的fileNameKey对应接收方controller处的@RequestParam(value = "file")里的名字,例如这里fileNameKey需要为file,否则接收方会报错 */
// 文件流
builder.addBinaryBody(fileNameKey, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
//表单中其他参数
if (paramMap != null && paramMap.size() > 0) {
for (Map.Entry entry : paramMap.entrySet()) {
builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
log.info("文件上传httpPost:[{}]", httpPost.toString());
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回
String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
return res;
}else{
log.error("文件请求res报错:{}", response);
}
} catch (Exception e) {
log.error("调用HttpPost失败:{}", e.toString(), e);
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
log.error("关闭HttpPost连接失败!");
}
}
}
return null;
}
}
版权声明:
作者:zhangchen
链接:https://www.techfm.club/p/44355.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
共有 0 条评论