有这么一个需求, 前端请求我的后端, 我的后端请求第三方的接口进行文字和图片的上传。
POM依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
controller: MultipartFile为数组,接收一个或多个文件
@RequestMapping(value = "/zlxf",method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public String sendfk(ZlxfDTO zlxfDTO, @RequestParam("files")MultipartFile[] files)
{
}
为项目中实际应用
httpclient post :
/**
*
* (doPostMultipartFile)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static String doPostMultipartFile(String url,Map<String,Object> map, MultipartFile[] files)throws Exception {
String result = "";
CloseableHttpClient client = HttpClients.createDefault();
//超时设置
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpPost post = new HttpPost(url);
post.setConfig(config);
try{
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = "";
MultipartFile multipartFile = null;
//text/plain ,不要用原生的,原生的是8859-1字符,会乱码
ContentType contentType = ContentType.create("application/json", Charset.forName("utf-8"));
//json文字内容
for(Map.Entry<String, Object> entry: map.entrySet())
{
if(null == entry.getValue())
{
continue;
}
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
//不要用原生的,原生的是8859-1字符,会乱码
ContentType contentType2 = ContentType.create("multipart/form-data", Charset.forName("utf-8"));
//一个或多个 文件, files,为参数名
for (int i = 0; i < files.length; i++)
{
multipartFile = files[i];
fileName = multipartFile.getOriginalFilename();
builder.addBinaryBody("files", multipartFile.getInputStream(), contentType2, fileName);
}
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
if(200 == response.getStatusLine().getStatusCode())
{
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity,"UTF-8");
}
}catch(HttpException e)
{
e.printStackTrace();
logger.error("---------http调用接口异常!",e);
ExceptionHelper.throwExc("http调用接口异常");
}finally{
//释放连接
post.releaseConnection();
}
return result;
}
工具类
package com.htcf.spbj.init;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htcf.frame.base.util.ExceptionHelper;
import com.htcf.frame.base.util.JsonUtil;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.params.HttpParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
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.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.zookeeper.Op.Create;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static String fileurl="http://68.174.33.43/service-spbj/uploadFile/upload";
/**
* (post)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static JSONObject post(String url, Map<String, Object> map) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpPost post = new HttpPost(url);
post.setConfig(config);
JSONObject obj = new JSONObject();
StringEntity entiry = new StringEntity(JsonUtil.toJsonNonNull(map), "utf-8");
try {
entiry.setContentEncoding("utf-8");
entiry.setContentType("application/json;charset=UTF-8");
post.setEntity(entiry);
HttpResponse response = client.execute(post);
if (200 == response.getStatusLine().getStatusCode()) {
String str = EntityUtils.toString(response.getEntity(), "utf-8");
obj = JSONObject.parseObject(str);
}
} catch (HttpException e) {
e.printStackTrace();
logger.error("---------http调用接口异常!", e);
ExceptionHelper.throwExc("http调用接口异常");
} finally {
//释放连接
post.releaseConnection();
}
return obj;
}
/**
* (post)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static String doPost(String url, Map<String, Object> map) throws Exception {
String result = "";
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpPost post = new HttpPost(url);
post.setConfig(config);
try {
/*StringEntity entiry = new StringEntity(JsonUtil.toJsonDefaults(map),"utf-8");
entiry.setContentEncoding("utf-8");
entiry.setContentType("application/json;charset=UTF-8");
post.setEntity(entiry);
HttpResponse response = client.execute(post);
*/
List<BasicNameValuePair> list = new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, (String) map.get(key));
list.add(basicNameValuePair);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
entity.setContentType("application/json;charset=UTF-8");
HttpResponse response = client.execute(post);
if (200 == response.getStatusLine().getStatusCode()) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
}
} catch (HttpException e) {
e.printStackTrace();
logger.error("---------http调用反馈接口异常!", e);
ExceptionHelper.throwExc("http调用反馈接口异常");
} finally {
//释放连接
post.releaseConnection();
}
return result;
}
/**
* (post)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static JSONArray doGet(String url) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
try {
HttpResponse response = client.execute(httpGet);
Header firstHeader = response.getFirstHeader("Content-Disposition");
String fileName = "未知.jpg";
if(null != firstHeader)
{
HeaderElement[] elements = firstHeader.getElements();
if(null != elements && elements.length > 0)
{
for (HeaderElement headerElement : elements)
{
NameValuePair parameterByName = headerElement.getParameterByName("filename");
if(null != parameterByName)
{
fileName = parameterByName.getValue();
}
}
}
}
if (200 == response.getStatusLine().getStatusCode()) {
byte[] readInputStream = readInputStream(response.getEntity().getContent());
return doPostMultipartFile(fileurl, readInputStream, fileName);
}
} catch (HttpException e) {
e.printStackTrace();
logger.error("---------http调用接口异常!", e);
ExceptionHelper.throwExc("http调用接口异常");
} finally {
//释放连接
httpGet.releaseConnection();
}
return null;
}
/**
* (post)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static String doGet(String url, Map<String, Object> map) throws Exception {
String result = "";
CloseableHttpClient client = new DefaultHttpClient();
if (map != null) {
Set<String> keySet = map.keySet();
for (String key : keySet) {
String value = (String) map.get(key);
value = URLEncoder.encode(value, "UTF-8");
value = URLEncoder.encode(value, "UTF-8");
url = url + "&" + key + "=" + value;
}
}
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
try {
HttpResponse response = client.execute(httpGet);
if (200 == response.getStatusLine().getStatusCode()) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
}
} catch (HttpException e) {
logger.error("---------http调用接口异常!", e);
ExceptionHelper.throwExc("http调用接口异常");
} finally {
//释放连接
client.close();
}
return result;
}
/**
* (doPostMultipartFile)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static String doPostMultipartFile(String url, Map<String, Object> map, MultipartFile[] files) throws Exception {
String result = "";
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpPost post = new HttpPost(url);
post.setConfig(config);
try {
/*List<BasicNameValuePair> list = new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key:keySet) {
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key,(String)map.get(key));
list.add(basicNameValuePair);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"utf-8");
entity.setContentType("application/json;charset=UTF-8");
post.setEntity(entity);*/
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = "";
MultipartFile multipartFile = null;
//text/plain
ContentType contentType = ContentType.create("application/json", Charset.forName("utf-8"));
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (null == entry.getValue()) {
continue;
}
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
ContentType contentType2 = ContentType.create("multipart/form-data", Charset.forName("utf-8"));
for (int i = 0; i < files.length; i++) {
multipartFile = files[i];
fileName = multipartFile.getOriginalFilename();
builder.addBinaryBody("files", multipartFile.getInputStream(), contentType2, fileName);
}
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (200 == response.getStatusLine().getStatusCode()) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
}
} catch (HttpException e) {
e.printStackTrace();
logger.error("---------http调用接口异常!", e);
ExceptionHelper.throwExc("http调用接口异常");
} finally {
//释放连接
post.releaseConnection();
}
return result;
}
/**
* (doPostMultipartFile)
*
* @param map 参数
* @return 返回结果
* @throws Exception
* @author tangjiandong
*/
public static JSONArray doPostMultipartFile(String url, byte[] by, String fileName) throws Exception {
JSONArray result = null;
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true).build();
HttpPost post = new HttpPost(url);
post.setConfig(config);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
MockMultipartFile mockMultipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), by);
ContentType contentType2 = ContentType.create("multipart/form-data", Charset.forName("utf-8"));
builder.addBinaryBody("files", mockMultipartFile.getInputStream(), contentType2 , fileName);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (200 == response.getStatusLine().getStatusCode()) {
HttpEntity resEntity = response.getEntity();
result = JSONObject.parseArray(EntityUtils.toString(resEntity, "UTF-8"));
}
} catch (HttpException e) {
e.printStackTrace();
logger.error("---------http调用接口异常!", e);
ExceptionHelper.throwExc("http调用接口异常");
} finally {
//释放连接
post.releaseConnection();
}
return result;
}
public static byte[] readInputStream(InputStream inputStream)
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] by = new byte[1024];
int len;
try {
while((len = inputStream.read(by)) != -1)
{
os.write(by, 0, len);
}
inputStream.close();
} catch (Exception e) {
logger.error("----------文件流读取异常!");
e.printStackTrace();
}
return os.toByteArray();
}
}