/** * 从微信服务器下载多媒体文件 *
* @param accessToken 微信accessToken* @param mediaId 微信媒体文件id * @param fileSavePath 保存的文件路径 */public static String downloadFromWxMediaId(String accessToken, String mediaId, String fileSavePath) throws IOException { if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(mediaId)){ return null; } // 微信公众号官方文档提供单url String download_media_url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; String requestUrl = download_media_url.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId); URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); InputStream in = conn.getInputStream(); File dir = new File(fileSavePath); if (!dir.exists()) { dir.mkdirs(); } if (!fileSavePath.endsWith("/")) { fileSavePath += "/"; } String contentDisposition = conn.getHeaderField("Content-disposition"); String contentLength = conn.getHeaderField("Content-Length"); String contentType = conn.getHeaderField("Content-Type"); String weixinServerFileName = contentDisposition.substring(contentDisposition.indexOf("filename") + 10, contentDisposition.length() - 1); fileSavePath += weixinServerFileName; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileSavePath)); byte[] data = new byte[1024]; int len = -1; while ((len = in.read(data)) != -1) { bos.write(data, 0, len); } bos.close(); in.close(); conn.disconnect(); return fileSavePath; }
从微信服务器下载多媒体文件
最新推荐文章于 2021-03-21 21:56:48 发布