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 urlBuilder = new URIBuilder(url);
post.setURL(urlBuilder.build());
} catch (URISyntaxException e) {
e.printStackTrace();
}
//封装请求头head
//( 千万千万不要把 "Content-Type":"multipart/form-data" 封装进请求头,否则会请求出错 )
//以下举例三条,根据需要调的接口的实际情况封装
//headMap.put("x-qys-accesstoken", accessToken);
//headMap.put("x-qys-timestamp", String.valueOf(timestamp));
//headMap.put("x-qys-signature", md5Str);
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;
}
}
扩展一:
1、上面工具类一般是用于我方图片传到对方服务器上,需要封装请求头的情况。
下面假设对方系统一般会给你一个图片url,需要上传到我服务器上。
//文件上传(不需要封装请求头的)
/*
* url:上传到我方需要调用的接口url
* fileName:文件名
* inputStream:需要上传的图片资源流
*
*/
public static String doPost(String url, String fileName, InputStream inputStream) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
// 文件流
builder.addBinaryBody("files", inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
2、实际调用仅供参考(对方一般会提供一个图片资源url,将url转成inputStream,再调用1中的接口即可)
//示例:提供一个图片url上传到远端服务器
List<Map<String, Object>> file0InfoList = getApplicationFormFileInfo(0, ytenantId);
for (int i = 0; i < file0InfoList.size(); i++) {
Map<String, Object> file0Map = file0InfoList.get(i);
//中间表id
String id = String.valueOf(file0Map.get("id"));
String applicationFormNo = String.valueOf(file0Map.get("application_form_no"));
String fileType = String.valueOf(file0Map.get("file_type"));
String fileUrl = String.valueOf(file0Map.get("file_url"));
String fileName = String.valueOf(file0Map.get("file_name"));
//需要上传图片资源的单据id
String formId = getReplaceApplicationFormId(fileType, applicationFormNo, ytenantId);
String suffix = null;
if (fileUrl.contains("jpeg")) {
suffix = ".jpeg";
} else if (fileUrl.contains("jpg")) {
suffix = ".jpg";
} else if (fileUrl.contains("png")) {
suffix = ".png";
} else if (fileUrl.contains("JPEG")) {
suffix = ".jpeg";
} else if (fileUrl.contains("JPG")) {
suffix = ".jpg";
} else if (fileUrl.contains("PNG")) {
suffix = ".png";
}
//(fileUrl是对方提供的需要上传的图片url)
URL url = new URL(UriUtils.encodePath(fileUrl, StandardCharsets.UTF_8));
//建立链接 获取流
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "plain/text;charset=" + StandardCharsets.UTF_8);
conn.setRequestProperty("charset", String.valueOf(StandardCharsets.UTF_8));
conn.setDoInput(true);
conn.setDoOutput(true);
inStream = conn.getInputStream();
//(saveFileUrl是我方服务器url)
String saveFileUrl = appConfig.getDomainUrl() + FILEURL + accessToken + "&businessType=" + BUSINESSTYPE + "&businessId=" + formId;
//(调用1中的doPost()方法)
String doPost = doPost(saveFileUrl, fileName + suffix, inStream);
if (StringUtils.isNotBlank(doPost)) {
JSONObject result = JSONObject.parseObject(doPost);
if ("200".equals(result.get("code"))) {
//上传完图片到BIP获取到返回的图片id
String fileId = ((Map<String, String>) (((JSONArray) (((JSONObject) result.get("data")).get("data"))).get(0))).get("id");
//更新version = 1 和 file_id
if (StringUtils.isNotBlank(fileId)) {
ApplicationFormFile applicationFormFile = new ApplicationFormFile();
applicationFormFile.setId(id);
applicationFormFile.setFileId(fileId);
applicationFormFile.setVersion(1);
applicationFormFile.setModifyTime(DateUtil.getNow());
applicationFormFile.setPubts(DateUtil.getNow());
int opr = applicationFormFileMapper.updateByPrimaryKeySelective(applicationFormFile);
}
} else {
log.error("附件保存异常: {}。请确认图片url资源可以访问:{}", doPost, fileUrl);
}
}
扩展二:获取不同接口的返回结果
1、获取接口返回的输入流(仅供参考)
//获取接口返回的输入流
try {
HttpResponse response = com.yonyou.iuap.utils.HttpUtil.getInstance().doPost(domain + url,null,paramMap,headMap);
InputStream inputStream = null;
if (response != null) {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
inputStream = resEntity.getContent();
}
}
return inputStream;
}
} catch (Exception e) {
log.info(ResultMessage.error(e.getMessage()));
}
2、获取接口返回的string类型数据(仅供参考)
//获取接口返回的string类型数据
HttpResponse response = HttpUtil.getInstance().doPost(delFileUrl, null, null);
if (response != null) {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String result = EntityUtils.toString(resEntity);
JSONObject jsonObject = JSONObject.parseObject(result);
if ("200".equals(jsonObject.get("code"))) {
//更新version = 0
ApplicationFormFile applicationFormFile = new ApplicationFormFile();
applicationFormFile.setId(id);
applicationFormFile.setVersion(0);
applicationFormFile.setModifyTime(DateUtil.getNow());
applicationFormFile.setPubts(DateUtil.getNow());
applicationFormFileMapper.updateByPrimaryKeySelective(applicationFormFile);
}
}
}
}