JAVA微信公众号开发之自动回复消息与图片
首先,應該建立一個消息與圖片的實體,看一下微信公眾號的文檔:
?
回復文本消息
| <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[你好]]></Content> </xml> |
?
?
| ToUserName | 是 | 接收方帳號(收到的OpenID) |
| FromUserName | 是 | 開發者微信號 |
| CreateTime | 是 | 消息創建時間 (整型) |
| MsgType | 是 | text |
| Content | 是 | 回復的消息內容(換行:在content中能夠換行,微信客戶端就支持換行顯示) |
回復圖片消息
| <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[image]]></MsgType> <Image> <MediaId><![CDATA[media_id]]></MediaId> </Image> </xml> |
?
| ToUserName | 是 | 接收方帳號(收到的OpenID) |
| FromUserName | 是 | 開發者微信號 |
| CreateTime | 是 | 消息創建時間 (整型) |
| MsgType | 是 | image |
| MediaId | 是 | 通過素材管理中的接口上傳多媒體文件,得到的id。 ? |
?
之后組裝實體,用戶發來消息或者事件時候給微信服務器發送請求,服務器把消息返回給在公眾號配置的服務器域名處,然后再進行邏輯判斷,給微信服務器返回消息,發給用戶。
?
下面給出一般的消息類型:
? ? ? ? public static final String MESSAGE_SCAN="SCAN";//未關注公眾號掃描二維碼
public static final String MESSAGE_TEXT="text";//文本
public static final String MESSAGE_IMAGE="image";//圖片
public static final String MESSAGE_VOICE="voice";//語音
public static final String MESSAGE_VIDEO="video";//視頻
public static final String MESSAGE_LINK="link";//連接
public static final String MESSAGE_LOCATION="location";//地理位置事件
public static final String MESSAGE_EVENT="event";//事件
public static final String MESSAGE_SUBSCRIBE="subscribe";//關注
public static final String MESSAGE_UNSUBSCRIBE="unsubscribe";//取消關注
public static final String MESSAGE_CLICK="CLICK";//點擊
public static final String MESSAGE_VIEW="VIEW";//t跳轉鏈接url
需要注意的是,發送圖片需要先把圖片上傳到微信服務器獲取MediaId,才能發給用戶。
?
/*** xml轉為map集合* @MethodName:xmlToMap*@author:maliran*@ReturnType:Map<String,String>*@param req*@return*@throws IOException*@throws DocumentException*/public static Map<String,String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException{Map<String,String> map = new HashMap<String,String>();SAXReader reader = new SAXReader();//log4j.jarInputStream ins = req.getInputStream();Document doc = reader.read(ins);Element root = doc.getRootElement();List<Element> list = root.elements();for(Element e:list){map.put(e.getName(), e.getText());}ins.close();return map;}/*** 文本轉換為xml* @MethodName:textMessageToXml*@author:maliran*@ReturnType:String*@param textMessage*@return*/public static String textMessageToXml(TextMessage textMessage){XStream xstream = new XStream();//xstream.jar,xmlpull.jarxstream.alias("xml", textMessage.getClass());//置換根節點System.out.println(xstream.toXML(textMessage));return xstream.toXML(textMessage);}/*** 圖片轉成xml* @MethodName:textMessageToXml*@author:maliran*@ReturnType:String*@param textMessage*@return*/public static String imageMessageToXml(ImageMessage imageMessage){XStream xstream = new XStream();//xstream.jar,xmlpull.jarxstream.alias("xml", imageMessage.getClass());//置換根節點//System.out.println(xstream.toXML(imageMessage));return xstream.toXML(imageMessage);}/*** 組裝圖片xml* @MethodName:initImageMessage*@author:maliran*@ReturnType:String*@param MediaId*@param toUserName*@param fromUserName*@return*/public static String initImageMessage(String MediaId,String toUserName,String fromUserName){ String message = null;Image image = new Image();ImageMessage imageMessage = new ImageMessage();image.setMediaId(MediaId);imageMessage.setFromUserName(toUserName);imageMessage.setToUserName(fromUserName);imageMessage.setCreateTime(new Date().toString());imageMessage.setImage(image);imageMessage.setMsgType(MESSAGE_IMAGE);message = imageMessageToXml(imageMessage);return message;}public static String initTextMessage(String content,String toUserName,String fromUserName){ String message = null;TextMessage textMessage = new TextMessage();textMessage.setFromUserName(toUserName);textMessage.setToUserName(fromUserName);textMessage.setCreateTime(new Date().toString());textMessage.setContent(content);textMessage.setMsgType(MESSAGE_TEXT);message = textMessageToXml(textMessage);return message;} /*** 上傳本地文件到微信獲取mediaId*/public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {File file = new File(filePath);if (!file.exists() || !file.isFile()) {throw new IOException("文件不存在");}String url = ConfigUtil.UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);URL urlObj = new URL(url);//連接HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();con.setRequestMethod("POST"); con.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false); //設置請求頭信息con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty("Charset", "UTF-8");//設置邊界String BOUNDARY = "----------" + System.currentTimeMillis();con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);StringBuilder sb = new StringBuilder();sb.append("--");sb.append(BOUNDARY);sb.append("\r\n");sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");sb.append("Content-Type:application/octet-stream\r\n\r\n");byte[] head = sb.toString().getBytes("utf-8");//獲得輸出流OutputStream out = new DataOutputStream(con.getOutputStream());//輸出表頭out.write(head);//文件正文部分//把文件已流文件的方式 推入到url中DataInputStream in = new DataInputStream(new FileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}in.close();//結尾部分byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定義最后數據分隔線out.write(foot);out.flush();out.close();StringBuffer buffer = new StringBuffer();BufferedReader reader = null;String result = null;try {//定義BufferedReader輸入流來讀取URL的響應reader = new BufferedReader(new InputStreamReader(con.getInputStream()));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}if (result == null) {result = buffer.toString();}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {reader.close();}}JSONObject jsonObj = JSONObject.fromObject(result);System.out.println(jsonObj);String typeName = "media_id";if(!"image".equals(type)){typeName = type + "_media_id";}String mediaId = jsonObj.getString(typeName);return mediaId;}?
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");String serverPath="";serverPath = req.getServletContext().getRealPath("/").replace("\\", "/"); //Servlet初始化時執行,如果上傳文件目錄不存在則自動創建 if(!new File(serverPath+"qrimage").isDirectory()){ new File(serverPath+"qrimage").mkdirs(); } PrintWriter out = resp.getWriter();//String openId = GetCookie.getCookie(req,resp);Map<String, String> map;try {map = MessageUtil.xmlToMap(req);String fromUserName = map.get("FromUserName");System.out.println(fromUserName);String toUserName = map.get("ToUserName");String msgType = map.get("MsgType");//String content = map.get("Content");String message = "";if(MessageUtil.MESSAGE_EVENT.equals(msgType)){ System.out.println("事件");String eventType = map.get("Event");System.out.println(eventType);String eventKey = map.get("EventKey");System.out.println(map.get("EventKey"));if(MessageUtil.MESSAGE_CLICK.equals(eventType)){String key = map.get("EventKey");if(key.equals("1")){String filePath = serverPath+"qrimage"+"\\"+fromUserName+".jpg"; //String url = "WebContent/qrimage/"+fromUserName+".jpg";String ticket = wxQRCodeService.createForeverStrTicket(fromUserName); //System.out.println(url);//獲取access_token String content = "123456";String mediaId = MyImageUtil.upload(filePath, accessToken,MessageUtil.MESSAGE_IMAGE);String imageMessage = MessageUtil.initImageMessage(mediaId, toUserName, fromUserName);System.out.println(imageMessage);out.print(imageMessage);out.close();}}}else{return; }} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}?
?
最近在整理一些資源工具,放在網站分享?http://tools.maqway.com
歡迎關注公眾號:麻雀唯伊 , 不定時更新資源文章,生活優惠,或許有你想看的
?
?
總結
以上是生活随笔為你收集整理的JAVA微信公众号开发之自动回复消息与图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 普通本科菜菜海淘无人搭理,苦心闭关修炼一
- 下一篇: php riak,PHP-Riak:快速