背景:
還是那個業務背景,面向微信公眾號開發,指定針對用戶發送消息,胖友們,我研究了一天了,代碼粘過去,用不了你錘死我
1、pom.xml文件中添加依賴
<!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.wso2.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.1.wso2v1</version> </dependency> <dependency> <groupId>org.wso2.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.1.wso2v1</version> </dependency> <!-- json --> <dependency> <groupId>top.jfunc.json</groupId> <artifactId>json-fastjson</artifactId> <version>1.8.3</version> </dependency>
DataEntity.java
@Getter @Setter public class DataEntity { //內容 private String value; //字體顏色 private String color; public DataEntity(String value ,String color){ this.value = value; this.color = color; }
實現類: 有“XXX”的地方需要修改,其他地方可以不用動
WechatMsg.java
@Component public class WechatMsg { public static void main(String[] args) { WechatMsg wm = new WechatMsg(); wm.SendWeChatMsg(wm.getToken()); } /** * 獲取token * * @return token */ public String getToken() { // 授予形式 String grant_type = "client_credential"; //應用ID String appid = "XXXXXXXXXXXXXXXXXXX"; //密鑰 String secret = "XXXXXXXXXXXXXXXXXXXXXXXXXX"; // 接口地址拼接參數 String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret; String tokenJsonStr = doGetPost(getTokenApi, "GET", null); JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr); String token = tokenJson.get("access_token").toString(); System.out.println("獲取到的TOKEN : " + token); return token; } /*** * 發送消息 * * @param token */ public void SendWeChatMsg(String token) { // 接口地址 String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; //openId String toUser = "XXXXXXXXXXXXXX"; //消息模板ID String template_id = "XXXXXXXXXXXXXXXXXXXXXX"; //整體參數map Map<String, Object> paramMap = new HashMap<String, Object>(); //消息主題顯示相關map Map<String, Object> dataMap = new HashMap<String, Object>(); //根據自己的模板定義內容和顏色 dataMap.put("first",new DataEntity("詳細內容XXXXXXX","#173177")); dataMap.put("keyword1",new DataEntity("私有化部署XXX","#173177")); dataMap.put("keyword2",new DataEntity("2020-08-18XXX" ,"#173177")); dataMap.put("remark",new DataEntity("申請成功XXX","#173177")); paramMap.put("touser", toUser); paramMap.put("template_id", template_id); paramMap.put("data", dataMap); System.out.println(doGetPost(sendMsgApi,"POST",paramMap)); } /** * 調用接口 post * @param apiPath */ public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){ OutputStreamWriter out = null; InputStream is = null; String result = null; try{ URL url = new URL(apiPath);// 創建連接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(type) ; // 設置請求方式 connection.setRequestProperty("Accept", "application/json"); // 設置接收數據的格式 connection.setRequestProperty("Content-Type", "application/json"); // 設置發送數據的格式 connection.connect(); if(type.equals("POST")){ out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8編碼 out.append(JSON.toJSONString(paramMap)); out.flush(); out.close(); } // 讀取響應 is = connection.getInputStream(); int length = (int) connection.getContentLength();// 獲取長度 if (length != -1) { byte[] data = new byte[length]; byte[] temp = new byte[512]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } result = new String(data, "UTF-8"); // utf-8編碼 } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } }
效果圖
附微信接口文檔:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html