1、添加依赖
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
</dependencies>
2、举例工具类(具体请求参数自调)
package com.xpf.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
public class MulFormDataUtils {
/**
* multipart/form-data格式接口调用
* @param headMap 请求头(自行根据调用接口封装)
* @param url
* @param paramMap 请求参数(自行根据调用接口封装)
* @param inputStream
* @return
*/
public static String doPostUploadFile(HashMap<String, Object> headMap, String url, HashMap<String, Object> paramMap, InputStream inputStream){
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost();
try {
URIBuilder builder = new URIBuilder(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//封装请求头head
//( 千万千万不要把 "Content-Type":"multipart/form-data" 封装进请求头,否则会请求出错 )
headMap.entrySet().forEach(p -> post.setHeader(p.getKey(), String.valueOf(p.getValue()) ));
//解决中文乱码问题
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY.withCharset("UTF-8"), String.valueOf(paramMap.get("title")));
//(这个是要调的接口的参数,根据实际情况组装)解决文件名中文乱码(???)
builder.addTextBody("title", String.valueOf(paramMap.get("title")), ContentType.DEFAULT_TEXT.withCharset("UTF-8"));
builder.addTextBody("fileType", String.valueOf(paramMap.get("fileType")));
HttpEntity entity = builder.build();
post.setEntity(entity);
String result = null;
try {
HttpResponse response = client.execute(post);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
|