备注:测试基于微信公众平台测试号编写,真实开发环境基本适用
微信公众号在进行视频群发的时候有一个坑,大家可以先看一下文档描述:
意思就是说要先把视频素材的media_id通过这个接口post一下,于是我下意识的就认为是在永久素材上传那里得到的media_id,但是后面总是返回40007错误,提示media_id不合法。
最后测试了很长时间,才发现视频发送的这里和文章群发一样有一个坑,这里说的media_id并不是通过永久素材上传接口那里获得的,而是要使用下面这个接口:
https://api.weixin.qq.com/cgi-bin/media/upload?access_token=access_token&type=TYPE
然后再用这个获取到的media_id去post才对,最后再用得到的最终的media_id进行群发。
下面是实现代码
注意:
1、因为测试号没有群发功能,所以使用的预览功能,在实际环境中替换一下即可
2、获取access_token的方法(即代码中的getaccess())使用自己的获取方法即可
/**
* 上传视频方法
*/
public static String postFile(String url, String filePath,
String title,String introduction) {
File file = new File(filePath);
if(!file.exists()){
return null;
}
String result = null;
try {
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
String boundary = "-----------------------------"+System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
OutputStream output = conn.getOutputStream();
output.write(("--" + boundary + "\r\n").getBytes());
output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
byte[] data = new byte[1024];
int len =0;
FileInputStream input = new FileInputStream(file);
while((len=input.read(data))>-1){
output.write(data, 0, len);
}
output.write(("--" + boundary + "\r\n").getBytes());
output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}",title,introduction).getBytes());
output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
output.flush();
output.close();
input.close();
InputStream resp = conn.getInputStream();
StringBuffer sb = new StringBuffer();
while((len= resp.read(data))>-1){
sb.append(new String(data,0,len,"utf-8"));
}
resp.close();
result = sb.toString();
System.out.println(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 请求接口
*/
public static String connectWeiXinInterface(String action,String json){
URL url;
try {
url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 传入参数
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println("请求返回结果:"+result);
os.flush();
os.close();
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 发送预览视频
*/
@RequestMapping("/sendvideo")
@ResponseBody
public String sendvideo(String id) throws KeyManagementException, NoSuchAlgorithmException, IOException{
//获取access_token
String access_token = getaccess();
//上传视频到微信服务器获取media_id
String path = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=video";
String postresult = postFile(path, "视频地址", "视频标题", "视频描述");
Map maps = (Map)JSON.parse(postresult);
String media1 = maps.get("media_id").toString();
//通过media_id获取发送media_id
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token="+access_token;
String twString="{\"media_id\": \""+media1+"\","+
"\"title\": \"视频标题\","+
"\"description\": \"视频描述\"}";
String result = connectWeiXinInterface(url, twString);
Map maps2 = (Map)JSON.parse(result);
String media2 = maps2.get("media_id").toString();
//根据media_id进行发送
String url2 = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token="+access_token;
String twString2="{\"touser\":\"okmRs6WO-DSlzVwiqwF3gfc3-pmk\","+
"\"mpvideo\":{\"media_id\":\""+media2+"\"},"+
"\"msgtype\":\"mpvideo\"}";
String result2 = connectWeiXinInterface(url2, twString2);
return result2;
}