6.9.4 下载多媒体文件

下载多媒体文件的请求地址如下:

  1. http://file.api.weixin.qq.com/cgi-bin/media/
  2. get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID

笔者将下载多媒体文件的操作封装成getMedia()方法,该方法的实现如下:

  1. /**
  2. * 下载媒体文件
  3. *
  4. * @param accessToken 接口访问凭证
  5. * @param mediaId 媒体文件标识
  6. * @param savePath 文件在服务器上的存储路径
  7. * @return
  8. */
  9. public static String getMedia(String accessToken, String mediaId, String savePath) {
  10. String filePath = null;
  11. // 拼接请求地址
  12. String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/
  13. media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
  14. requestUrl = requestUrl.replace("ACCESS_TOKEN",
  15. accessToken).replace("MEDIA_ID", mediaId);
  16. try {
  17. URL url = new URL(requestUrl);
  18. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  19. conn.setDoInput(true);
  20. conn.setRequestMethod("GET");
  21.  
  22. if (!savePath.endsWith("/")) {
  23. savePath += "/";
  24. }
  25. // 根据内容类型获取扩展名
  26. String fileExt = CommonUtil.getFileExt(conn.getHeaderField("Content-Type"));
  27. // 将mediaId作为文件名
  28. filePath = savePath + mediaId + fileExt;
  29.  
  30. BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
  31. FileOutputStream fos = new FileOutputStream(new File(filePath));
  32. byte[] buf = new byte[8096];
  33. int size = 0;
  34. while ((size = bis.read(buf)) != -1)
  35. fos.write(buf, 0, size);
  36. fos.close();
  37. bis.close();
  38.  
  39. conn.disconnect();
  40. log.info("下载媒体文件成功,filePath=" + filePath);
  41. } catch (Exception e) {
  42. filePath = null;
  43. log.error("下载媒体文件失败:{}", e);
  44. }
  45. return filePath;
  46. }

注意 下载多媒体文件接口不支持下载视频文件,只支持下载图片、语音和缩略图文件。