2022-12-29 15:11:09.053 [http-nio-21111-exec-1] INFO n.s.f.w.s.r.HttpClientService [executePostFormData:313]
- http post 上传文件 请求url:https://api.weixin.qq.com/cgi-bin/media/upload?access_token=64_aslJtoIlWLkfdj5LajPZbkvcM9Oop6cqMuCdXiepThCLgutJpM_vfNJ9F7ETAhSj0KCTbZfxY_-HaHkEzvG4oAgig5UhTVosISGnlJ8DpPRWhPmK_7Q7c0LLZMkBQKeABAPEY&type=image, param:{access_token=64_aslJtoIlWLkfdj5LajPZbkvcM9Oop6cqMuCdXiepThCLgutJpM_vfNJ9F7ETAhSj0KCTbZfxY_-HaHkEzvG4oAgig5UhTVosISGnlJ8DpPRWhPmK_7Q7c0LLZMkBQKeABAPEY, type=image}, header:null,body:media
2022-12-29 15:11:09.839 [http-nio-21111-exec-1] INFO n.s.f.w.s.r.HttpClientService [executePostFormData:321]
- http post 上传文件 返回原始值 result:{"errcode":41005,"errmsg":"media data missing hint: [C2uS0869p448] rid: 63ad3d8d-7090d9a6-1cb04ba0"}
/**
* POST请求form-data处理上传文件
*
* @param <T>
* @param url 地址
* @param header 请求头
* @param paramMap 请求参数
* @param fileParamName 请求体的参数名
* @param file 文件
* @param clazz 返回的类型
* @return
*/
public <T> T executePostFormData(String url, Map<String, String> header, Map<String, Object> paramMap,
String fileParamName, File file, Class<T> clazz) {
CloseableHttpResponse response = null;
T responseResult = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
// 判断请求参数不为空
if (paramMap != null) {
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
HttpPost httpPost = new HttpPost(uriBuilder.build());
// 判断请求头不为空
if (header != null && header.size() > 0) {
header.forEach(httpPost::addHeader);
}
// 构建请求体
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 设置浏览器兼容模式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置请求的编码格式
builder.setCharset(Consts.UTF_8);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
// 添加文件
builder.addBinaryBody(fileParamName, file);
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
// 使用HttpClient发起请求,返回response
log.info("http post 上传文件 请求url:{}, param:{}, body:{}", httpPost.getURI(), paramMap, fileParamName);
response = httpClient.execute(httpPost);
if (response == null) {
return null;
}
String result = EntityUtils.toString(response.getEntity(), Charset.forName(DEFAULT_ENCODE));
log.info("http post 上传文件 返回原始值 result:{}", result);
if (StringUtils.isNotEmpty(result)) {
responseResult = JSON.parseObject(result, clazz);
}
} catch (Exception e) {
log.error("executePost error", e);
} finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
// 返回结果
return responseResult;
}
临时素材接口不支持java调用 狗头