一、业务需求:
需要请求第三方接口上传文件,该请求类型是form-data请求
二、postmant请求结果如下
三、maven依赖:
org.apache.httpcomponents
httpcore
4.4.9
org.apache.httpcomponents
httpclient
4.5.13
org.apache.httpcomponents
httpmime
4.5.12
四、java实现请求
public static void test() {
String goodsUrl = "http://0.0.0.0:7000/pangu/";
//本地文件位置
String fileName = "D:\222.png";
String str = null;
try {
//添加请求头
HashMap map = new HashMap();
//map.put("token", CommonConstant.token);
File file = new File(fileName);
str = doPostUploadFile(goodsUrl + "/sacw/CommonConfig/uploadFile", map, file);
if(file.exists()) {
//boolean delete = file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* post请求提交form-data上传文件
*
* @param url 上传地址
* @param headers 请求头
* @param file 上传文件
* @return
*/
public static String doPostUploadFile(String url, Map headers, File file) {
HttpPost httpPost = new HttpPost(url);
packageHeader(headers, httpPost);
String fileName = file.getName();
CloseableHttpResponse response = null;
String respContent = null;
long startTime = System.currentTimeMillis();
// 设置请求头 boundary边界不可重复,重复会导致提交失败
String boundary = "-------------------------" + UUID.randomUUID().toString();
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// 创建MultipartEntityBuilder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 设置字符编码
builder.setCharset(StandardCharsets.UTF_8);
// 模拟浏览器
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置边界
builder.setBoundary(boundary);
// 设置multipart/form-data流文件
builder.addPart("sendfile", new FileBody(file));
builder.addTextBody("fileType", "1");
// application/octet-stream代表不知道是什么格式的文件
builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() paramsHeads, HttpRequestBase httpMethod) {
if (null!= paramsHeads && paramsHeads.size()>0) {
Set
注意:这里的builder.addPart("sendfile", new FileBody(file));
,multipartFile
对应form表单的字段名称。
参考:Java发送form-data请求实现文件上传_IceFloe_Rot的博客-CSDN博客