业务背景 上传商品到第三方平台,需要先将商品的图片地址换成该平台的图片地址
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());
}
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;
}
|