/**
* 上传图文消息内的图片获取URL
* https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
*
* @param image
* @return
*/
@Override
public String uploadImg(MultipartFile image) {
String imageURL = null;
try {
String token = this.getToken();
imageURL = this.uploadImage(token, image.getBytes());
} catch (Exception e) {
throw new RuntimeException(e);
}
return imageURL;
}
/**
* 上传图片
*
* @param accessToken
* @param imageBytes
* @return
* @throws Exception
*/
public String uploadImage(String accessToken, byte[] imageBytes) throws Exception {
String url = String.format("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=%s", accessToken);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("media", "image.jpg",
RequestBody.create(MediaType.parse("image/jpg"), imageBytes))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
JSONObject jsonObject = JSONObject.parseObject(result);
String imageURL = jsonObject.getString("url");
return imageURL;
} else {
throw new Exception("请求未成功,错误代码:" + response.code());
}
}