下载网络图片上传至微信临时素材,获取madea_id;
读取本地图片同样适用,只需获取本地文件输入流,调用upLoadImageToWeChat()方法即可:
getMediaId
public String getMediaId(String imgUrl) {
String mediaId = "";
if (StringUtils.isNotEmpty(imgUrl)) {
OkHttpClient client = new OkHttpClient();
Request req = new Request.Builder().url(imgUrl).build();
Response resp = null;
try {
resp = client.newCall(req).execute();
if (resp.isSuccessful()) {
ResponseBody body = resp.body();
InputStream inputStream = body.byteStream();
mediaId = upLoadImageToWeChat(inputStream, imgUrl);
}
} catch (IOException e) {
logger.error("下载网络图片出错!{}", e);
throw new ServiceException(e.getMessage(), e);
}
}
return mediaId;
}
upLoadImageToWeChat
private String upLoadImageToWeChat(InputStream inputStream, String filename) throws IOException {
String url = weChatMediaUploadUrl + "?access_token=" + loginService.getWeChatAccessToken() + "&type=image";
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
String result = null;
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type",
"multipart/form-data; boundary="
+ BOUNDARY);
int length = inputStream.available();
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + length + "\";filename=\""
+ filename + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = inputStream.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
inputStream.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
Map<String, Object> map = JSONObject.parseObject(result, Map.class);
if (map.containsKey("media_id")) {
return map.get("media_id").toString();
} else {
logger.error("小程序上传临时素材出错,返回信息为: {} " + JSON.toJSONString(result));
throw new ServiceException("小程序上传临时素材出错,返回信息为:" + JSON.toJSONString(result));
}
}