微信公众号下载媒体文件到个人服务器或本地:
下载多媒体文件
公众号可调用本接口来获取多媒体文件。请注意,视频文件不支持下载,调用该接口需http协议。
首先封装一个下载文件的类:
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import net.sf.json.JSONObject;
import xxx.Enum.EnumMethod;
import xxx.Pojo.MdlUpload;
import xxx.Pojo.Result;
public class DownloadUtil {
private static final String download_url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
private static final String upload_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
public static SimpleDateFormat Dateformat = new SimpleDateFormat("/yyyy/MM/dd/HH/mm/ss/");
// 凭证无效时,保证只重做一次,不死循环
private static HashMap<String, Integer> mapRedo = new HashMap<String, Integer>();
/**
* 下载文件
*
* @param accessToken
* @param media_id
* @param path
* @return null为成功
*/
public static String Download(String accessToken, String media_id, String path) {
String url = download_url.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", media_id);
byte[] data = HttpRequestUtil.httpRequest_byte(url, EnumMethod.GET.name(), null);
if (data.length < 100) {
String s = new String(data);
if (s.startsWith("{") && s.endsWith("}")) {
return s;
}
}
try {
FileOutputStream os = new FileOutputStream(path);
os.write(data);
os.close();
return null;
} catch (Exception e) {
e.printStackTrace();
JSONObject jsonObject = new JSONObject();
jsonObject.put("assn_err_msg", "Download Exception:" + e.toString());
return jsonObject.toString();
}
}
/**
* 上传文件
*
* @param accessToken
* @param type
* @param file
* @return
*/
public static Result<MdlUpload> Upload(String accessToken, String type, File file) {
Result<MdlUpload> result = new Result<MdlUpload>();
String url = upload_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
JSONObject jsonObject;
try {
HttpPostUtil post = new HttpPostUtil(url);
post.addParameter("media", file);
String s = post.send();
jsonObject = JSONObject.fromObject(s);
if (jsonObject.containsKey("media_id")) {
MdlUpload upload=new MdlUpload();
upload.setMedia_id(jsonObject.getString("media_id"));
upload.setType(jsonObject.getString("type"));
upload.setCreated_at(jsonObject.getString("created_at"));
result.setObj(upload);
result.setErrmsg("success");
result.setErrcode("0");
} else {
result.setErrmsg(jsonObject.getString("errmsg"));
result.setErrcode(jsonObject.getString("errcode"));
}
} catch (Exception e) {
e.printStackTrace();
result.setErrmsg("Upload Exception:"+e.toString());
}
return result;
}
/**
* 根据URL下载文件
*
* @param basePath
* 上传文件服务器地址
* @param url
* 文件URL
* @param type
* 文件类型
* @param extensionName
* 扩展名
* @return
*/
public static Result<String> DownloadCommon(String basePath, String url, String type, String extensionName) {
Result<String> result = new Result<String>();
Date d = new Date();
String vPath = "/wx/" + type + Dateformat.format(d);
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extensionName;
String pPath = basePath + vPath;
pPath = pPath.replace('\\', File.separatorChar);
pPath = pPath.replace('/', File.separatorChar);
File dirFile = new File(pPath);
dirFile.mkdirs();
pPath += fileName;
vPath += fileName;
String s = null;
[] data = HttpRequestUtil.httpRequest_byte(url, EnumMethod.GET.name(), null);
if (data == null || data.length == 0) {
s = "下载失败";
} else {
try {
FileOutputStream os = new FileOutputStream(pPath);
os.write(data);
os.close();
catch (Exception e) {
e.printStackTrace();
s = e.toString();
}
if (s == null) {
System.out.println("pPath="+pPath);
result.setObj(vPath);
return result;
}
result.setErrmsg(s);
return result;
}
EnumMethod.class
package xxx.Enum;
public enum EnumMethod {
GET,POST;
}
MdlUpload.class
public class MdlUpload {
private String type;
private String media_id;
private String created_at;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMedia_id() {
return media_id;
}
public void setMedia_id(String mediaId) {
media_id = mediaId;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String createdAt) {
created_at = createdAt;
}
public MdlUpload() {
super();
}
@Override
public String toString() {
return "MdlUpload [created_at=" + created_at + ", media_id=" + media_id + ", type=" + type + "]";
}
}
最后在抽取一个调用类,使用简洁:
import java.io.File;
import xxx.MdlUpload;
import xxx.Pojo.Result;
/**
* 微信号文件操作类
*
* @author Sunlight
*
*/
public class FileUtil {
/**
* 下载文件
* @param media_id 媒体Id
* @param path 路径
* @return
*/
public static String Download(String token,String media_id, String path) {
return DownloadUtil.Download(token, media_id, path);
}
/**
* 上传文件
* @param type
* @param file
* @return
*/
public static Result<MdlUpload> Upload(String token,String type, File file) {
return DownloadUtil.Upload(token, type, file);
}
/**
* 下载文件
* @param basePath
* @param url
* @param type
* @param extensionName
* @return
*/
public static Result<String> DownloadCommon(String basePath, String url, String type, String extensionName){
return DownloadUtil.DownloadCommon(basePath, url, type, extensionName);
}
}
测试下载文件方法:
private static String token;
static {
token = Wechat.Util.getAccessToken("appid", "appSecret").getToken();//此处调用获取AccessToken的方法
System.out.println("token=" + token);
}
@Test
public void testDownload() {
// path =="" 表示下载成功
String path = FileUtil.Download(token, "1LatptxLLGpJDUCvTaSFpyX_0ixELCp2AQzj3oryIEr4qJp9zRTfVr5j_Co1XJbPmhRNS34eRXX-PZxLWUyDXHg", "E:\\aaa.jpg");
System.out.println("path=" + path);
}
@Test
public void testUpload() {
File file = new File("E:\\xxx.mp3");
System.err.println(file.getName());
Result<MdlUpload> result = FileUtil.Upload(token, EnumMessageType.voice.name(), file);
System.out.println("Errcode=" + result.getErrcode() + "\tErrmsg=" + result.getErrmsg());
System.out.println(result.getObject().toString());
}
@Test
public void testDownloadCommon() {
String basePath="/\\192.168.1.111\\FilesPath";
Result<String> result=FileUtil.DownloadCommon(basePath, "http://wx.qlogo.cn/mmhead/Q3auHgzwzM67JZASQrxTwcpzZccSBvG3U9uIHgUJP26SibMUEH3ymwg/0","image", "jpg");
System.out.println("errCode="+result.getErrcode()+"\t\tmsg="+result.getErrmsg());
System.err.println("path="+result.getObject());
}