【微信公衆號開發】根據openId羣發消息

根據開發文檔可知,只要使用POST方式提交固定格式的json字符串到那個地址便可。這裏我寫的是最簡單的文本java

第一步:創建對應的實體類。json

 1 package cn.sp.bean;
 2 
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 /**羣發消息
 7  * Created by 2YSP on 2017/7/12.
 8  */
 9 public class MassMessage {
10     private List<String> touser;
11     private String msgtype;
12     private Map<String,Object> text ;
13 
14     public List<String> getTouser() {
15         return touser;
16     }
17 
18     public void setTouser(List<String> touser) {
19         this.touser = touser;
20     }
21 
22     public String getMsgtype() {
23         return msgtype;
24     }
25 
26     public void setMsgtype(String msgtype) {
27         this.msgtype = msgtype;
28     }
29 
30     public Map<String, Object> getText() {
31         return text;
32     }
33 
34     public void setText(Map<String, Object> text) {
35         this.text = text;
36     }
37 }

第二步:編寫測試類:api

 

 1 package cn.sp.test;
 2 
 3 import cn.sp.bean.AccessToken;
 4 import cn.sp.bean.MassMessage;
 5 import cn.sp.utils.WeiXinUtil;
 6 import com.google.gson.Gson;
 7 import com.google.gson.GsonBuilder;
 8 import net.sf.json.JSONObject;
 9 
10 import java.util.ArrayList;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14 
15 /**
16  * Created by 2YSP on 2017/7/12.
17  */
18 public class Test {
19     public static final String URL = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
20 
21     public static void main(String[] args) {
22         //獲取token
23         AccessToken token = WeiXinUtil.getAccessToken();
24         String url = URL.replace("ACCESS_TOKEN", token.getToken());
25 
26 
27         MassMessage massMessage = new MassMessage();
28         List<String> list = new ArrayList<String>();
29         list.add("o2fVHwF3EYXzhWa9a_UNlC5TNrEk");
30         list.add("o2fVHwF3EYXzhWa9a_UNlC5TNrEk");
31         massMessage.setTouser(list);
32         massMessage.setMsgtype("text");
33         Map<String, Object> map = new HashMap<String, Object>();
34         map.put("content", "hello,<a href='https://www.baidu.com'>點我去百度了</a>");
35         massMessage.setText(map);
36 
37         Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
38         String str = gson.toJson(massMessage);
39         System.out.println("str:"+str);
40 
41         JSONObject jso = WeiXinUtil.doPostStr(url, str);
42         System.out.println(jso.toString());
43     }
44 }

這裏是使用httpClient發起的請求,gson將對象轉換爲json字符串。測試

注意openId至少爲兩個,不然返回報錯不能發送,若是隻有一個openId的話能夠寫兩遍。ui

效果如圖:this

相關文章
相關標籤/搜索