import org.nutz.lang.Files; //导入方法依赖的package包/类
protected void download(String openid, String media_id, String url) {
File f = new File(mediaPath(openid, media_id));
if (f.exists() && f.length() > 1) {
log.info("Media aready exit > " + media_id);
return;
}
for (int i = 0; i < 3; i++) {
InputStream in = null;
OutputStream out = null;
File tmp = null;
try {
if (Strings.isBlank(url)) {
url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + wxctx.getAPI(openid).getAccessToken() + "&media_id=" + media_id;
}
Response resp = Http.get(url, 60*1000);
if (resp.isOK()) {
in = resp.getStream();
tmp = File.createTempFile("nutzwx_media", ".media");
out = new FileOutputStream(tmp);
Streams.writeAndClose(out, in);
// 检查一下是不是报错
if (tmp.length() < 128) {
byte[] data = Files.readBytes(f);
if (data[0] == '{') { // 看上去是个json,悲催了...
// 多媒体文件怎么可能是{开头,抛错吧
throw new IllegalArgumentException("mediaId="+media_id+ ","+new String(data));
//try {
//NutMap map = Json.fromJson(NutMap.class, new String(data));
//if (map.containsKey("errcode") && map.getInt("errcode") != 0) {
//log.warn("download media fail >> " + new String(data));
//}
//} catch (Throwable e) {
//log.debug("not a json? ok", e);
//}
}
}
if (f.exists())
f.delete();
Files.makeDir(f.getParentFile());
tmp.renameTo(f);
WxMedia media = new WxMedia(media_id, resp.getHeader().getInt("Content-Length", 0), resp.getHeader().get("Content-Type"));
Json.toJsonFile(new File(f.getAbsolutePath()+".info"), media);
log.debug("media download success mediaId="+media_id);
break;
} else {
log.debugf("download %s fail, code=%s, content=%s", media_id, resp.getStatus(), resp.getContent());
}
} catch (Throwable e) {
log.infof("download %s fail", media_id, e);
} finally {
Streams.safeClose(in);
Streams.safeClose(out);
if (tmp != null)
tmp.delete();
}
}
}