背景:业务需求是在公众号里自动回复二维码图片,自动回复用的图片事先已经上传至公司文件服务器;以下是执行成功代码
1、将图片链接转换成文件
private File getFileByUrl(String picUrl, String suffix) throws Exception {
URL imageUrl = new URL(picUrl);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
File file = File.createTempFile("pattern", "." + suffix);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(outputStream.toByteArray());
inputStream.close();
outputStream.close();
fileOutputStream.close();
return file;
}
2、上传至微信服务器
public String doPostWithFormData(String url, File file, String fileType, String paramName) {
RequestBody fileBody = RequestBody.create(MediaType.parse(fileType), file);
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(paramName, file.getName(),fileBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(multipartBody)
.build();
return getResult(request);
}
private String getResult(Request request) {
if (null == request) {
log.error("http 请求 request 不能为 null");
return null;
}
String message = null;
long beginTime = System.nanoTime();
try {
Response response = client.newCall(request).execute();
if (response.body() != null) {
message = response.body().string();
}
} catch (Exception e) {
log.error(" 请求 {} , 执行时间 : {}, 报错{}", request.toString(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime), e);
}
log.info(" 请求 {} , 执行时间 : {}", request.toString(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime));
return message;
}
3、调用
public String uploadTempImage(String picUrl){
if (StringUtils.isBlank(picUrl)) {
return null;
}
String accessToken = "";// 公司的accessToken
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?type=image&access_token=" + accessToken;
String result = null;
try {
String suffix = picUrl.substring(picUrl.lastIndexOf(".")+1, picUrl.length());
File file = getFileByUrl(picUrl, suffix);
String fileType = "image/jpeg";
if ("png".equalsIgnoreCase(suffix)) {
fileType = "image/png";
}
result = HttpClientUtils.getInstance().doPostWithFormData(url, file, fileType, "media");
file.delete();
} catch (Exception e) {
log.warn("uploadTempImage,failed", e);
}
log.info("uploadTempImage,result={}", result);
return Optional.ofNullable(result)
.map(s -> JsonUtils.toBean(s, Map.class))
.map(map -> (String)map.get("media_id")).orElse(null);
}
4、遇到的问题
(1){“errcode”:41005,“errmsg”:“media data missing hint: [ZiYG1a0115d418]”}
可能原因:传参时方法错误,错误方法 addPart(fileBody)
我的解决:.addFormDataPart(paramName, file.getName(),fileBody)
文件参数名传空也行
(2)java media data missing hint: [hPxMUa0729hb93]
这个稀里糊涂就解决了,后来也没试出是哪里错了