這篇文章主要回顧WeiXinMY微信查詢公衆號是如何聯網請求成績。java
第一部分:建立菜單git
一、拿到APPID和ACCESS_TOKEN_URL,經過doGetStr方法請求jsonObject獲取token,此處token是以後建立菜單必須參數。github
public class WeiXinUtil { private static final String APPID = "wx1ba5329fcb5a3b62"; private static final String APPSECRET = "e80f628a6be76d02aa847fce805b801b"; private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; //get請求 public static JSONObject doGetStr(String url){ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); JSONObject jsonObject = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonObject; } //post請求 public static JSONObject doPostStr(String url,String outStr){ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); JSONObject jsonObject = null; try { httpPost.setEntity(new StringEntity(outStr,"UTF-8")); HttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity(),"UTF-8"); jsonObject = JSONObject.fromObject(result); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } //獲取access_token public static AccessToken getAccessToken(){ AccessToken token = new AccessToken(); String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET); JSONObject jsonObject = doGetStr(url); if(jsonObject!=null){ token.setToken(jsonObject.getString("access_token")); token.setExpiresIn(jsonObject.getInt("expires_in")); } return token; } }
二、組裝菜單和建立菜單json
//組裝菜單 public static Menu initMenu(){ Menu menu = new Menu(); ClickButton button11 = new ClickButton(); button11.setName("所有成績"); button11.setType("click"); button11.setKey("11"); ClickButton button12 = new ClickButton(); button12.setName("必修課績點"); button12.setType("click"); button12.setKey("12"); Button button1 = new Button(); button1.setName("查詢成績"); button1.setSub_button(new Button[]{button11,button12}); ViewButton button21 = new ViewButton(); button21.setName("綁定學號"); button21.setType("view"); button21.setUrl("http://ap18458589.iok.la/WeiXinMY/index.jsp"); ClickButton button22 = new ClickButton(); button22.setName("重置"); button22.setType("click"); button22.setKey("22"); Button button2 = new Button(); button2.setName("學號管理"); button2.setSub_button(new Button[]{button21,button22}); ClickButton button31 = new ClickButton(); button31.setName("掃碼"); button31.setType("scancode_push"); button31.setKey("31"); ClickButton button32 = new ClickButton(); button32.setName("地理位置"); button32.setType("location_select"); button32.setKey("32"); Button button3 = new Button(); button3.setName("功能菜單"); button3.setSub_button(new Button[]{button31,button32}); menu.setButton(new Button[]{button1,button2,button3}); return menu; } public static int createMenu(String token,String menu){ int result = 0; String url = CREATE_MEN_URL.replace("ACCESS_TOKEN", token); JSONObject jsonObject = doPostStr(url,menu); if(jsonObject != null){ result = jsonObject.getInt("errcode"); } return result; }
三、WeiXinTest.java用於獲取token建立菜單api
package com.myangtzeu.test; import java.util.ArrayList; import java.util.List; import com.myangtzeu.menu.Menu; import com.myangtzeu.pojo.AccessToken; import com.myangtzeu.utils.SpiderUtil; import com.myangtzeu.utils.WeiXinUtil; import net.sf.json.JSONObject; public class WeiXinTest { public static void main(String[] args) { try { AccessToken token = WeiXinUtil.getAccessToken(); System.out.println("票據:"+token.getToken()); System.out.println("有效時間:"+token.getExpiresIn()); String menu = JSONObject.fromObject(WeiXinUtil.initMenu()).toString(); System.out.println(menu); int result = WeiXinUtil.createMenu(token.getToken(), menu); if(result==0){ System.out.println("建立菜單成功"); }else{ System.out.println("錯誤碼:"+result); } } catch (Exception e) { e.printStackTrace(); } } }
第二部分:請求數據微信
一、MessageUtil,初始化成績查詢事件,返回xml,爬蟲和具體代碼詳見github。session
//所有成績事件 public static String initCj(String toUserName,String fromUserName,String account,String password){ String message = null; List<News> newsList = new ArrayList<News>(); NewsMessage newsMessage = new NewsMessage(); News news = new News(); news.setTitle("您的所有成績以下:"); SpiderUtil su = new SpiderUtil(); List<String> list = new ArrayList<String>(); su.spiderCj(account, password, list); StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if(i%2 == 0){ sb.append(":"); }else{ sb.append("\n"); } } news.setDescription(sb.toString()+"\n\n"+"回覆【所有成績】查全部成績\n"+"回覆【績點】查看績點\n"+"回覆【重置】從新綁定學號"); // news.setPicUrl("http://ap18458589.iok.la/WeiXinMY/WebRoot/image/IMG_6497.PNG"); news.setUrl("www.yuol.online:8080"); newsList.add(news); newsMessage.setToUserName(fromUserName); newsMessage.setFromUserName(toUserName); newsMessage.setCreateTime(new Date().getTime()); newsMessage.setMsgType(MESSAGE_NEWS); newsMessage.setArticles(newsList); newsMessage.setArticleCount(newsList.size()); message = newsMessageToXml(newsMessage); return message; }
二、經過監聽MESSAGE_CLICK,實現成績消息推送app
package com.myangtzeu.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.myangtzeu.utils.CheckUtil; import com.myangtzeu.utils.MessageUtil; public class WeiXinServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); if(CheckUtil.checkSignature(signature, timestamp, nonce)){ out.print(echostr); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { Map<String,String> map = MessageUtil.xmlToMap(request); String fromUserName = map.get("FromUserName"); String toUserName = map.get("ToUserName"); String msgType = map.get("MsgType"); String content = map.get("Content"); String message = null; if(MessageUtil.MESSAGE_TEXT.equals(msgType)){ if("1".equals(content)){ message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenu()); }else if("2".equals(content)){ message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.secondMenu()); }else if("M".equals(content) || "m".equals(content)){ message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText()); } // TextMessage text = new TextMessage(); // text.setFromUserName(toUserName); // text.setToUserName(fromUserName); // text.setMsgType("text"); // text.setCreateTime(new Date().getTime()); // text.setContent("�����͵���Ϣ�ǣ�"+content); // message = MessageUtil.textMessageToXml(text); }else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){ String eventType = map.get("Event"); String eventKey = map.get("EventKey"); if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){ message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText()); }else if(MessageUtil.MESSAGE_CLICK.equals(eventType)){ if(eventKey.equals("11")){ HttpSession session = request.getSession(); String account = (String) session.getAttribute("account"); String password = (String) session.getAttribute("password"); message = MessageUtil.initCj(toUserName, fromUserName, account, password); System.out.println(account); }else if(eventKey.equals("12")){ message = MessageUtil.initJd(toUserName, fromUserName); }else if(eventKey.equals("22")){ response.sendRedirect("InvalidateServlet"); message = MessageUtil.initCz(toUserName, fromUserName); } }else if(MessageUtil.MESSAGE_VIEW.equals(eventType)){ String url = map.get("EventKey"); message = MessageUtil.initText(toUserName, fromUserName, url); }else if(MessageUtil.MESSAGE_SCANCODE.equals(eventType)){ String key = map.get("EventKey"); message = MessageUtil.initText(toUserName, fromUserName, key); } }else if(MessageUtil.MESSAGE_LOCATION.equals(msgType)){ String label = map.get("Label"); message = MessageUtil.initText(toUserName, fromUserName, label); } out.print(message); } catch (Exception e) { e.printStackTrace(); }finally{ out.close(); } } }