下载多媒体文件
公众号可调用本接口来获取多媒体文件。请注意,视频文件不支持下载,调用该接口需http协议。
接口调用请求说明
http请求方式: GET
http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
请求示例(示例为通过curl命令获取多媒体文件)
curl -I -G "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"
参数说明
参数 |
是否必须 |
说明 |
access_token |
是 |
调用接口凭证 |
media_id |
是 |
媒体文件ID |
返回说明
正确情况下的返回HTTP头如下:
HTTP/1.1 200 OK
Connection: close
Content-Type: image/jpeg
Content-disposition: attachment; filename="MEDIA_ID.jpg"
Date: Sun, 06 Jan 2013 10:20:18 GMT
Cache-Control: no-cache, must-revalidate
Content-Length: 339721
curl -G "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"
错误情况下的返回JSON数据包示例如下(示例为无效媒体ID错误)::
{"errcode":40007,"errmsg":"invalid media_id"}
使用网页调试工具调试该接口
演示代码例子:
package com.gta.test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.gta.tool.WeixinUtils;
public class DownloadFromWeiXinServer {
public static String access_token =null;
////个人订阅号或者公众号的appId和appSecret
//
public static String appId="xxxxxxxxxxxxxx";
//
public static String appSecret="xxxxxxxxxxxxxx";
//微信平台测试账号的appId和appSecret
public static String appId ="xxxxxxxxxx";
public static String appSecret ="xxxxxxxxxxx";
static{
//通过微信公众号的appId和appSecret的值,初始化加载获取access_token值
access_token=WeixinUtils.getAccessToken(appId, appSecret);
}
public static void main(String[] args) throws Exception {
String mediaId="hKs64_xKpwb3Hbp5nBj0tqDRSwUoZOpGtdfHoYo0DYknFaVApe7DrNU4W9thnfvZ";
String savePath="D:\\";
String saveFileName="xxx.jpg";
download(access_token, mediaId,savePath,saveFileName);
}
/**
* 微信公众平台下载多媒体文件
* @param accessToken//
* @param mediaId//要下载的多媒体文件ID
* @author xueshi.zhu
* @throws Exception
*/
public static void download(String accessToken,String mediaId,String savePath,String saveFileName) throws Exception {
try {
// 拼装请求地址
String downloadMediaUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
downloadMediaUrl=downloadMediaUrl.replaceAll("ACCESS_TOKEN", accessToken);
downloadMediaUrl=downloadMediaUrl.replaceAll("MEDIA_ID", mediaId);
URL url = new URL(downloadMediaUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
InputStream in=con.getInputStream();
InputStream inStream = in;
byte[] data = readInputStream(inStream);
File mediaFile = new File(savePath+saveFileName);
FileOutputStream outStream = new FileOutputStream(mediaFile);
outStream.write(data);
outStream.close();
System.out.println(in.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
================================================================================================================================
package com.gta.tool;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 微信接口工具类。
* 注意getAccessToken里对accessToken的处理。
*
*/
/**
* 微信接口工具类。
* 注意getAccessToken里对accessToken的处理。
*
*/
public class WeixinUtils {
//存储最后一次获取accessToken的时间,因为一个token可用2个小时,频繁调用token会被禁
public static Map accessTokenTimeMapping = new HashMap();
public static Map accessTokenMapping = new HashMap();
/**
* 获取AccessToken。
* @param appId
* @param appSecret
* @return
*/
public static String getAccessToken(String appId, String appSecret) { // 获得ACCESS_TOKEN
long nowTime = System.currentTimeMillis();
String key = appId+"_"+appSecret;
//调试的时候,获取一次token,然后把值放在这里。
if(false)return "knQf-j-L8iXHsp0U9ymtLIJR2spxwrwnuftp-MHpYhb_5Lyn8nnhfAdtqP9GGfWelaZdFoCzDf4vGPHGr6vHfQ";
Long lstAccessTokenTime = accessTokenTimeMapping.get(key);
if(lstAccessTokenTime == null)lstAccessTokenTime = 0l;
if( nowTime - lstAccessTokenTime < 7000 * 1000){
String accessToken = accessTokenMapping.get(key);
if(accessToken != null)
return accessToken;
}
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appId + "&secret=" + appSecret;
String message = weixinRequest(url,null,"GET");
try {
JSONObject demoJson = new JSONObject(message);
String accessToken = demoJson.getString("access_token");
System.out.println("WeixinManager.getAccessToken()"+message);
accessTokenTimeMapping.put(key, nowTime);
accessTokenMapping.put(key, accessToken);
return accessToken;
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
}
/**
* 设置微信的菜单。
* @param appId
* @param appSecret
* @param menu
* @return
* @throws IOException
*/
public static String resetMenu(String appId, String appSecret, String menu) throws IOException {
//[{
//"name":"最新活动","sub_button":
//[{"type":"click","name":"优惠活动","key":"m_discount"},
//{"type":"click","name":"积分查询","key":"m_query"}
//]
//}]
String access_token = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="
+ access_token;
String message = weixinRequest(url,menu,"POST");
return message;
}
/**
* 获取粉丝列表。
* @param appId
* @param appSecret
* @return
*/
public static JSONObject getFollowers(String appId, String appSecret){
return getFollowers(appId,appSecret,null);
}
/**
* 获取粉丝列表。
* @param appId
* @param appSecret
* @param nextOpenId 粉丝过万需要
* @return
*/
public static JSONObject getFollowers(String appId, String appSecret, String nextOpenId){
String access_token = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token;
if(nextOpenId != null && !"".equals(nextOpenId)) url+="&next_openid="+nextOpenId;
String rtn = weixinRequest(url,null,"GET");
System.out.println("WeixinManager.getUsers()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 获取粉丝的详细信息。
* @param appId
* @param appSecret
* @param openId
* @return
*/
public static JSONObject getFollowerInfo(String appId, String appSecret, String openId){
String accessToken = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
String rtn = weixinRequest(url, null, "GET");
System.out.println("WeixinManager.getFollowerInfo()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 创建群组
* @param appId
* @param appSecret
* @param groupName 群组名称
* @return 如{"group": { "id": 107, "name": "test" } }
*/
public static JSONObject createGroup(String appId, String appSecret, String groupName){
String accessToken = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + accessToken;
JSONObject j = new JSONObject();
try {
j.put("group", new JSONObject().put("name",groupName));
} catch (JSONException e) {
e.printStackTrace();
}
String rtn = weixinRequest(url, j.toString(), "POST");
System.out.println("WeixinManager.createGroup()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 查询所有分组
* @param appId
* @param appSecret
* @return
*/
public static JSONObject getAllGroups(String appId, String appSecret){
String accessToken = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + accessToken;
String rtn = weixinRequest(url, null, "GET");
System.out.println("WeixinManager.getAllGroups()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 通过用户的OpenID查询其所在的GroupID
* @param appId
* @param appSecret
* @param openId 用户的OpenID
* @return 如:{ "groupid": 102 }
*/
public static JSONObject getUserGroup(String appId, String appSecret, String openId){
String accessToken = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=" + accessToken;
JSONObject j = new JSONObject();
try {
j.put("openid", openId);
} catch (JSONException e1) {
e1.printStackTrace();
}
String rtn = weixinRequest(url, j.toString(), "POST");
System.out.println("WeixinManager.createGroup()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 发送模板消息
* @param appId
* @param appSecret
* @param openId 用户的openID
* @param templateId 模板id
* @param data 模板中各参数的赋值内容
* @return
*/
public static JSONObject sendTemplateMsg(String appId, String appSecret,String openId,
String templateId,
String detailUrl,
String topcolor,
String[] data){
String accessToken = getAccessToken(appId, appSecret);
String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
JSONObject postJson=new JSONObject();
try {
postJson.put("touser", openId);
postJson.put("template_id", templateId);
if(detailUrl != null)
postJson.put("url", detailUrl);
if(topcolor != null)
postJson.put("topcolor", topcolor);
JSONObject dataJson = new JSONObject();
for (int i = 0; i < data.length; i+=3) {
JSONObject k = new JSONObject();
k.put("value", data[i+1]);
if(data[i+2] != null)
k.put("color", data[i+2]);
dataJson.put(data[i], k);
}
postJson.put("data", dataJson);
} catch (JSONException e) {
e.printStackTrace();
}
String rtn = weixinRequest(url, postJson.toString(), "POST");
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 修改分组名
* @param appId
* @param appSecret
* @param groupId
* @param newGroupName
* @return 如 {"errcode": 0, "errmsg": "ok"}
*/
public static JSONObject updateGroup(String appId, String appSecret, String groupId, String newGroupName){
String accessToken = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + accessToken;
JSONObject j = new JSONObject();
JSONObject group = new JSONObject();
try {
j.put("id", groupId);
j.put("name",newGroupName);
group.put("group",j);
} catch (JSONException e) {
e.printStackTrace();
}
String rtn = weixinRequest(url, group.toString(), "POST");
System.out.println("WeixinManager.createGroup()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 移动用户分组
* @param appId
* @param appSecret
* @param toGroupId 新分组的id
* @param openId 用户id
* @return 如 {"errcode": 0, "errmsg": "ok"}
*/
public static JSONObject updateUserGroup(String appId, String appSecret, String toGroupId, String openId){
String accessToken = getAccessToken(appId, appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + accessToken;
JSONObject j = new JSONObject();
try {
j.put("openid", openId);
j.put("to_groupid", toGroupId);
} catch (JSONException e) {
e.printStackTrace();
}
String rtn = weixinRequest(url, j.toString(), "POST");
System.out.println("WeixinManager.createGroup()"+rtn);
JSONObject json;
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 上传多媒体文件
* @param appId
* @param appSecret
* @param type 文件类型
* @param filePath 文件的绝对路径
* @return 含有media_id的json数据
* @throws IOException
*/
public static JSONObject uploadMedia(String appId, String appSecret, String type, String filePath) throws IOException{
String accessToken = getAccessToken(appId, appSecret);
String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + type;
File file=new File(filePath);
// SimpleHttpClient shc = SimpleHttpClient.getInstance();
// Map m = new HashMap();
// m.put("media", new File(""));
// shc.upload(url, m);
URL urlObj = new URL(url);
// 连接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
//设置关键值
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String rtn = null;
JSONObject json;
try {
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
//System.out.println(line);
buffer.append(line);
}
if(rtn==null){
rtn = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if(reader!=null){
reader.close();
}
}
try {
json = new JSONObject(rtn);
} catch (JSONException e) {
throw new RuntimeException(e.getMessage(),e);
}
return json;
}
/**
* 获取图文消息的media_id
* @param appId
* @param appSecret
* @param infoMapList 图文消息的相关信息,Map中必须包括filePath(缩略图绝对地址), content 群发时必须有title
* @return
*/
public static JSONObject uploadnews(String appId, String appSecret, List