微信的群发功能个人觉得比较复杂一点
1.如果是纯文字的群发比较简单
2.如果是图片的,需要获取thumb_media_id
3.如果是图文信息,需要获取thumb_media_id
获取thumb_media_id,需要先上传媒体资源到服务器,且必须是永久的,调用的接口如下所示:
其中media类型共有5种
图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
视频(video):10MB,支持MP4格式
缩略图(thumb):64KB,支持JPG格式
代码演示:
public static void getMediaId(String appId,String appSecret) {
String addImage = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
//上传临时素材
String addImage2 = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=thumb";
//上传永久素材
String addImage3 = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=thumb";
String filepath ="src/main/webapp/image/1.jpg";
AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
String token = at.getToken();
//临时素材上传
/* String url = addImage2.replace("ACCESS_TOKEN",token);
UploadFile.postFile(url,filepath,"Hello World","shshsuhsushsh");*/
//上传永久素材
String url2 = addImage3.replace("ACCESS_TOKEN",token);
UploadFile.postImgFile(url2,filepath);
File file = new File("src/main/webapp/image/1.jpg");
System.out.print(file.exists());
}
public class UploadFile {
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) {
logger.error("postFile,不支持http协议",e);
} catch (IOException e) {
logger.error("postFile数据传输失败",e);
}
logger.info("{}: result={}",url,result);
return result;
}
//上传图片
public static String postImgFile(String url, String filePath) {
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: image/jpeg \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(("\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();
}
System.out.println(result);
return result;
}
这样就可以获取到thumb_media_id,接下来就是群发的功能了。
说到群发的话,这里我用测试号测试了只有文本的可以进行群发,其他的都不成功,官网写着根据标签进行群发【订阅号与服务号认证后均可用】,没交钱没办法,只能试试阉割版的咯。
public static String sendGroupMessage(String token){
String groupUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";//ACCESS_TOKEN是获取到的access_token,根据分组id发群发消息地址
String groupUrl1 = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
String url = groupUrl1.replace("ACCESS_TOKEN",token);
String openid1data = "{\"touser\":[\"oBLL2wL5GlPE5wo3ihbmU0VxE7qs\",\"oBLL2wGrduSANLkm4BheKclWCcKQ\"],\"msgtype\": \"text\",\"text\": {\"content\": \"测试文本666消息\"}}";
String group1data = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"3\"},\"text\":{\"content\":\"群发消息测试\"},\"msgtype\":\"text\"}";
JSONObject json = CommUtil.httpRequest(url, "POST", openid1data);
return json.toString();
}
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
以上代码仅供参考,未在真实环境测过,不知性能如何
参考资料
http://blog.csdn.net/oarsman/article/details/51538078
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729
http://blog.csdn.net/heboy19/article/details/49815611
http://www.cnblogs.com/h–d/p/5638092.html
http://lib.csdn.net/article/wechat/55774