业务背景
上传商品到第三方平台,需要先将商品的图片地址换成该平台的图片地址
/**
* POST请求发送MultipartFile文件参数
*/
public String doPostFile(String url, List<String> imageUrls, String fileParName,
int timeout) {
String resultMap = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (String imageUrl : imageUrls) {
byte[] bytes = HttpUtil.downloadBytes(imageUrl);
builder.addBinaryBody(fileParName, bytes, ContentType.MULTIPART_FORM_DATA, UUID.randomUUID().toString());// 文件流
}
//决中文乱码
// ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
org.apache.http.HttpResponse response = httpClient.execute(httpPost);// 执行提交
// 设置连接超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
httpPost.setConfig(requestConfig);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
resultMap = result;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultMap;
}