遇到一个调用文件下载接口,然后将返回值作为参数调用文件上传接口需求。特作此记录
// 调用文件下载接口,获取MultipartFile 对象(url为一个文件下载的请求路径,如果在浏览器中打开则会直接下载文件)
public static MultipartFile sendHttpGetMultipartFile(String url, HashMap<String, String> cookies,String originalFilename) {
// http调用接口
CloseableHttpResponse httpResponse = null;
byte[] bytes = null;
MultipartFile fileResult = null;
CloseableHttpClient httpClient = null;
InputStream inputStream = null;
try {
//获取http客户端(可以理解为先需要一个浏览器,但实际上httpclient和浏览器是不同的)
httpClient = HttpClientBuilder.create().build();
//创建get请求
HttpPost httpGet = new HttpPost(url);
StringJoiner joiner = new StringJoiner(";");
cookies.forEach((k,v)->joiner.add(k+"="+v));
httpGet.setHeader("Cookie",joiner.toString());
//客户端执行请求
httpResponse = httpClient.execute(httpGet);
//从响应模型中获取响应实体
HttpEntity entity = httpResponse.getEntity();
bytes = EntityUtils.toByteArray(entity);
inputStream = new ByteArrayInputStream(bytes);
fileResult = new MockMultipartFile(originalFilename,originalFilename,ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
} catch (Exception e) {
log.error("cmd:getFileStream 接口调用失败-", e);
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (inputStream != null) {
inputStream.close();
}
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
log.error("cmd:sendHttpGetMultipartFile | result=关闭资源失败", e);
}
}
return fileResult;
}
// 将上一步得到的MultipartFile对象作为参数,调用另一个文件上传接口
//1.先创建一个MultipartEntityBuilder 对象,相当于表单提交的参数,file是调用上面的接口获取到的MultipartFile对象
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("param1", "XXX");
try {
builder.addBinaryBody("param", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, name);
} catch (IOException e) {
log.error("错误",e);
}
// 2.url是文件上传接口
public static JSONObject httpPostFormFile(String url, MultipartEntityBuilder entityBuilder) {
String result;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
// .register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
// 创建自定义的httpclient对象
client = HttpClients.custom().setConnectionManager(connManager).build();
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
// 构造消息头
// httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
httpPost.setHeader("Accept", "application/json");
//配置代理
RequestConfig requestConfig = RequestConfig.custom()
// .setProxy(new HttpHost("localhost", 8888))
.build();
httpPost.setConfig(requestConfig);
// 设置参数到请求对象中
httpPost.setEntity(entityBuilder.build());
try {
response = client.execute(httpPost);
} catch (IOException e) {
log.error("httpPostFormFile 执行错误", e);
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
return new JSONObject();
}
//responseEntity才是真正收到的内容
HttpEntity responseEntity = response.getEntity();
result = "";
if (responseEntity != null) {
try {
result = EntityUtils.toString(responseEntity, "UTF-8");
} catch (IOException e) {
log.error("httpPostFormFile 执行错误", e);
}
}
try {
EntityUtils.consume(responseEntity);
} catch (IOException e) {
log.error("httpPostFormFile 执行错误", e);
}
} finally {
try {
if (client != null) {
client.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error("sendHttpGetMultipartFile | result=关闭资源失败", e);
}
}
return JSONObject.parseObject(result);
}