java开发微信订阅号群发功能(二)
获取到access_tocken之后就可以群发消息了
先试试群发文本消息
以下是官方文档介绍:
群发消息的接口如下
"https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+accessToken;
参数返回值如下
@RequestMapping("/messTextMessage")
@ResponseBody
public boolean messTextMessage(@RequestBody ArrayList<WxSubscribeProduct> productList) {
try {
Map<String, String> stringMap = this.getToken();
String accessToken = stringMap.get("access_token");
String phone = stringMap.get("phone");
String reqUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+accessToken;
try {
// 构造httprequest设置
HttpUrlConnectionToInterface httpsUtil = new HttpUrlConnectionToInterface();
StringBuffer content = new StringBuffer();
Map<String, Object> param = new HashMap<String, Object>();
for (WxSubscribeProduct wxSubscribeProduct : productList) {
content.append(wxSubscribeProduct.getGrade()).append("/").
append(wxSubscribeProduct.getManufactor()).append("/").
append(wxSubscribeProduct.getOneLevelClassification()).append("/").
append(wxSubscribeProduct.getThreeLevelClassification()).append("/").
append(wxSubscribeProduct.getTwoLevelClassification()).append("/").
append(wxSubscribeProduct.getSpecifications()).append("/").
append("\r\n");
}
content.append("联系电话:").append(phone).append("\n");
System.out.println(content.toString());
Text text = new Text();
text.setContent(content.toString());
Filter filter = new Filter();
filter.setIsToAll(true);
String msgtype = "text";
param.put("filter",filter);
param.put("text",text);
param.put("msgtype",msgtype);
JSONObject object = JSONObject.fromObject(param);
String msg = "";
String str = httpsUtil.doPostOrGet(reqUrl,object.toString());
System.out.println(param.toString());
// System.out.println("wX_ReturnMsg=="+str);
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
由于参数需要JSON格式,所以创建了两个java实体类一个Filter一个Text
Filter:
package com.zm.mall.domain.wxmsg;
/**
* Created by Administrator on 2020/5/6.
*/
public class Filter {
private Boolean is_to_all;
private String tag_id;
public Boolean getIsToAll() {
return is_to_all;
}
public void setIsToAll(Boolean is_to_all) {
this.is_to_all = is_to_all;
}
public String getTag_id() {
return tag_id;
}
public void setTag_id(String tag_id) {
this.tag_id = tag_id;
}
}
在发送图文消息需要将 is_to_all 参数赋值为 true
在发送图文消息不需要tag_id参数
Text:
package com.zm.mall.domain.wxmsg;
/**
* Created by Administrator on 2020/5/6.
*/
public class Text {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
content:发送文本消息时文本的内容
发送http请求时使用的工具类HttpURLConnection
package com.zm.mall.util.wechatutil;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Administrator on 2020/4/30.
*/
public class HttpUrlConnectionToInterface {
public static String doPostOrGet(String pathUrl, String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//请求方式
conn.setRequestMethod("POST");
//conn.setRequestMethod("GET");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
conn.setDoOutput(true);
conn.setDoInput(true);
/**
* 下面的三句代码,就是调用第三方http接口
*/
//获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//发送请求参数即数据
out.write(data);
//flush输出流的缓冲
out.flush();
/**
* 下面的代码相当于,获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
return result;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null){
out.close();
}
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] doPost(String pathUrl, String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//请求方式
conn.setRequestMethod("POST");
//conn.setRequestMethod("GET");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
conn.setDoOutput(true);
conn.setDoInput(true);
/**
* 下面的三句代码,就是调用第三方http接口
*/
//获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//发送请求参数即数据
out.write(data);
//flush输出流的缓冲
out.flush();
/**
* 下面的代码相当于,获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
byte[] bytes = result.getBytes();
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null){
out.close();
}
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
这样就完成了群发消息的文本消息群发,但是群发文本消息是有字数限制的。在发送字数过多的文本消息的时候不建议使用