微信图片下载

/**
   * 获取媒体文件
   * @param accessToken 接口访问凭证
   * @param media_id 媒体文件id
   * @param savePath 文件在服务器上的存储路径
   * */
  public static String downloadMedia(String accessToken, String mediaId, String savePath) {
    String filePath = null;
    // 拼接请求地址
    String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
    requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
    System.out.println(requestUrl);
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoInput(true);
      conn.setRequestMethod("GET");

      if (!savePath.endsWith("/")) {
        savePath += "/";
      }
      // 根据内容类型获取扩展名
      String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
      // 将mediaId作为文件名
      filePath = savePath + mediaId + fileExt;

      BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
      FileOutputStream fos = new FileOutputStream(new File(filePath));
      byte[] buf = new byte[8096];
      int size = 0;
      while ((size = bis.read(buf)) != -1)
        fos.write(buf, 0, size);
      fos.close();
      bis.close();

      conn.disconnect();
      String info = String.format("下载媒体文件成功,filePath=" + filePath);
      System.out.println(info);
    } catch (Exception e) {
      filePath = null;
      String error = String.format("下载媒体文件失败:%s", e);
      System.out.println(error);
    }
    return filePath;
  }

你可能感兴趣的:(微信)