场景:客户端(浏览器)A---->选择文件上传---->服务器B---->中转文件---->服务器C---->返回结果---->服务器B---->客户端A
有时候在项目中需要把上传的文件中转到第三方服务器,第三方服务器提供一个接收文件的接口。
而我们又不想把文件先上传到服务器保存后再通过File来读取文件上传到第三方服务器,我们可以使用HttpClient来实现。
因为项目使用的是Spring+Mybatis框架,文件的上传采用的是MultipartFile,而FileBody只支持File。
所以这里采用MultipartEntityBuilder的addBinaryBody方法以数据流的形式上传。
httpPostInvoke请求文件和String,httpPostInvokeJson只请求Json
这里需要引入两个jar包:httpclient-4.4.jar和httpmime-4.4.jar
Maven pom.xml引入
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
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.StringEntity;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.UUID;
@Slf4j
public class NetworkUtil {
public static int CONNECTTIMEOUT = 30000;
public static int SOCKETTIMEOUT = 90000;
public static String httpPostInvoke(String url, Map<String, Object> map, Map<String, Object> headerMap) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTTIMEOUT).setSocketTimeout(SOCKETTIMEOUT).build();
httpPost.setConfig(requestConfig);
if (headerMap != null && headerMap.size() > 0) {
for (Map.Entry entry : headerMap.entrySet()) {
if (entry.getValue() != null) {
httpPost.setHeader(entry.getKey().toString(), (String) entry.getValue());
}
}
}
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue() instanceof byte[]) {
multipartEntityBuilder.addBinaryBody(entry.getKey().toString(), (byte[]) entry.getValue(), ContentType.MULTIPART_FORM_DATA, UUID.randomUUID().toString().replaceAll("-", "")+".jpg");
} else {
multipartEntityBuilder.addPart(entry.getKey().toString(), new StringBody(entry.getValue().toString(), ContentType.TEXT_PLAIN));
}
}
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httpPost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httpPost);
String str = null;
try {
str = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.info("StatusLine:" + response.getStatusLine() + " executing request:" + httpPost.getRequestLine() + " request params:" + map + " response result:" + str);
}
log.info("executing request:" + httpPost.getRequestLine() + " request params:" + map + " response result:" + str);
EntityUtils.consume(response.getEntity());
return str;
} finally {
response.close();
try {
httpclient.close();
} catch (IOException e) {
log.error(String.format("httpPostInvoke error %s", e.getMessage()), e);
}
}
}
public static String httpPostInvokeJson(String url, Map<String, Object> bodyMap, Map<String, Object> headerMap) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTTIMEOUT).setSocketTimeout(SOCKETTIMEOUT).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("content-type", "application/json;charset=UTF-8");
if (headerMap != null && headerMap.size() > 0) {
for (Map.Entry entry : headerMap.entrySet()) {
if (entry.getValue() != null) {
httpPost.setHeader(entry.getKey().toString(), (String) entry.getValue());
}
}
}
String params = JSON.toJSONString(bodyMap);
StringEntity entity = new StringEntity(params, Charset.forName("UTF-8"));
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
String str = null;
try {
str = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.info("StatusLine:" + response.getStatusLine() + " executing request:" + httpPost.getRequestLine() + " request params:" + bodyMap + " response result:" + str);
}
log.info("executing request:" + httpPost.getRequestLine() + " request params:" + bodyMap + " response result:" + str);
EntityUtils.consume(response.getEntity());
return str;
} finally {
response.close();
try {
httpClient.close();
} catch (IOException e) {
log.error(String.format("httpPostInvoke error %s", e.getMessage()), e);
}
}
}