一、maven:
org.apache.httpcomponents
httpmime
4.5.3
二、工具类:
import java.io.File;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpConnectionFactory;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.routing.HttpRoute;
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.FileBody;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicLineParser;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import lombok.extern.slf4j.Slf4j;
/**
* @Auther: zyx.
* @Date: 2018/11/19 20:03
*/
@Slf4j
public class HttpUtils {
public static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/" +
"537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36";
public static String httpPostForFile(String url, Map fileMap, Map params,
Map headers) {
HttpClient httpClient = buildHttpClient();
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeaders(buildHeader(headers));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if (fileMap != null && fileMap.size() > 0) {
for (Entry file : fileMap.entrySet()) {
FileBody fileBody = new FileBody((File) file.getValue(), ContentType.DEFAULT_BINARY);
builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart(file.getKey(), fileBody);
}
}
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
for (Map.Entry entry : params.entrySet()) {
if (entry.getValue() == null)
continue;
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
String result = "";
Integer statusCode = response.getStatusLine().getStatusCode();
if (StrUtils.isNotEmpty(statusCode) && statusCode.intValue() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
} else {
log.error("请求地址" + url + "错误状态" + response.getStatusLine().getStatusCode());
EntityUtils.consume(entity);
}
return result;
} catch (Exception e) {
log.error(e.getMessage());
}
return "";
}
public static HttpClient buildHttpClient() {
HttpConnectionFactory httpConnectionFactory = new ManagedHttpClientConnectionFactory(
new DefaultHttpRequestWriterFactory(),
new DefaultHttpResponseParserFactory(new MyLineParser(),
new DefaultHttpResponseFactory()));
PoolingHttpClientConnectionManager pccm = new PoolingHttpClientConnectionManager(
httpConnectionFactory);
pccm.setDefaultMaxPerRoute(50);
pccm.setMaxTotal(300);
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(15000)
.setSocketTimeout(60000)
.setConnectTimeout(40000).build())
.setRedirectStrategy(new LaxRedirectStrategy())
.setConnectionManager(pccm)
.setRetryHandler(new DefaultHttpRequestRetryHandler(1, true))
.setUserAgent(DEFAULT_USER_AGENT).build();
return httpClient;
}
public static Header[] buildHeader(Map params) {
Header[] headers = null;
if (params != null && params.size() > 0) {
headers = new BasicHeader[params.size()];
int i = 0;
for (Map.Entry entry : params.entrySet()) {
headers[i] = new BasicHeader(entry.getKey(), entry.getValue());
i++;
}
}
return headers;
}
/**
* 如果返回不规范的HTTP头,实现兼容.
*/
private static class MyLineParser extends BasicLineParser {
@Override
public Header parseHeader(
CharArrayBuffer buffer) throws ParseException {
try {
return super.parseHeader(buffer);
} catch (ParseException ex) {
return new BasicHeader("Invalid",buffer.toString());
}
}
}
}
三、发送端参数包装:
public static List> builderSendFile(SyncLibrary sync, File file, int index, int splitNum) {
List> list = new ArrayList<>();
Map textMap = new HashMap<>();
textMap.put("methodType", sync.getMethodType());
textMap.put("splitNum", splitNum);
textMap.put("index", index);
textMap.put("libId", sync.getLibId());
textMap.put("appkey", sync.getAppkey());
Map fileMap = new HashMap<>();
fileMap.put("fileData", file);
list.add(textMap);
list.add(fileMap);
return list;
}
四、Spring controller接收:
@ResponseBody
@RequestMapping(value = "/feature/file/receive")
public ReceiveResponse receiveDate(@RequestParam(value = "fileData", required = false) MultipartFile multipartFile,
SyncSendDto dto) {