To start public platform development, we must first understand what the platform can help us do? To start public platform development, we must first understand what the platform can help us do?
Use your public account to log on to Alibaba Cloud.
I. communication mechanism
2. implement the GET method
We know from the document that we need to implement the POST and GET methods. the GET method is used to verify communication with you, and the POST method is used for message processing.
Create a Servlet HelloWeChat and first implement the GET method.
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO for the sake of simplicity, do not verify the response of the message source first. setContentType ("text/html; charset = UTF-8"); PrintWriter pw = response. getWriter (); String echo = request. getParameter ("echostr"); echo = new String (echo. getBytes ("ISO-8859-1"), "UTF-8"); pw. println (echo );}
Can I use http: // localhost: 8080/QiyadengWeb/HelloWeChat locally? Echostr = hello (Chinese). perform the test first. if there is no problem, deploy it on the server and set it on the public platform.
3. implement the POST method
The POST method first receives the XML sent from the public platform and extracts the message sender and content. More message content, you can add your own processing logic, and finally assemble it into a reply message XML, and return it to the public platform.
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = UTF-8"); PrintWriter pw = response. getWriter (); String wxMsgXml = IOUtils. toString (request. getInputStream (), "UTF-8"); WeChatTextMessage textMsg = null; try {textMsg = getWeChatTextMessage (wxMsgXml);} catch (Exception e) {e. printStackTra Ce ();} StringBuffer replyMsg = new StringBuffer (); if (textMsg! = Null) {// add the processing logic you need. here we just repeat the message replyMsg. append ("the message you sent me is:"); replyMsg. append (textMsg. getContent ();} else {replyMsg. append (":) is not a text message, and I cannot understand it for now");} String returnXml = getReplyTextMessage (replyMsg. toString (), textMsg. getFromUserName (); pw. println (returnXml );}
For debugging, we recommend a tool named Fiddler. you can simulate POST messages to your local machine instead of deploying them to the server for debugging each time. For how to use POST data of Fiddler, refer to the annotation content.
5. dependent libraries
If you are using maven, add the following dependencies. If you are not a maven user, find these libraries and add them to the buider path.
joda-time
joda-time
2.2
org.apache.commons
commons-io
1.3.2
com.thoughtworks.xstream
xstream
1.4.3
6. complete code
Package com. qiyadeng. wechat; import java. io. IOException; import java. io. printWriter; import java. util. date; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. io. IOUtils; import com. thoughtworks. xstream. XStream; import com. thoughtworks. xstream. io. xml. domD River;/*** Servlet implementation class HelloWeChat */public class HelloWeChat extends HttpServlet {private static final long serialVersionUID = 1L;/*** @ see HttpServlet # HttpServlet () */public HelloWeChat () {super ();}/*** @ see HttpServlet # doGet (HttpServletRequest request, HttpServletResponse response) */protected void doGet (HttpServletRequest request, HttpServletResponse response) throw S ServletException, IOException {// TODO for the sake of simplicity, the message source is not verified response first. setContentType ("text/html; charset = UTF-8"); PrintWriter pw = response. getWriter (); String echo = request. getParameter ("echostr"); echo = new String (echo. getBytes ("ISO-8859-1"), "UTF-8"); pw. println (echo);}/*** @ see HttpServlet # doPost (HttpServletRequest request, HttpServletResponse response) */protected void doPost (HttpServletR Equest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = UTF-8"); PrintWriter pw = response. getWriter (); String wxMsgXml = IOUtils. toString (request. getInputStream (), "UTF-8"); WeChatTextMessage textMsg = null; try {textMsg = getWeChatTextMessage (wxMsgXml);} catch (Exception e) {e. printStackTrace ();} StringBuffer replyMsg = n Ew StringBuffer (); if (textMsg! = Null) {// add the processing logic you need. here we just repeat the message replyMsg. append ("the message you sent me is:"); replyMsg. append (textMsg. getContent ();} else {replyMsg. append (":) is not a text message, and I cannot understand it for now");} String returnXml = getReplyTextMessage (replyMsg. toString (), textMsg. getFromUserName (); pw. println (returnXml);} private WeChatTextMessage getWeChatTextMessage (String xml) {XStream xstream = new XStream (new DomDriver (); xstream. alias ("xml", WeChatTextMessage. class); xstream. aliasField ("ToUserName", WeChatTextMessage. class, "toUserName"); xstream. aliasField ("FromUserName", WeChatTextMessage. class, "fromUserName"); xstream. aliasField ("CreateTime", WeChatTextMessage. class, "createTime"); xstream. aliasField ("MsgType", WeChatTextMessage. class, "messageType"); xstream. aliasField ("Content", WeChatTextMessage. class, "content"); xstream. aliasField ("MsgId", WeChatTextMessage. class, "msgId"); WeChatTextMessage wechatTextMessage = (WeChatTextMessage) xstream. fromXML (xml); return wechatTextMessage;} private String getReplyTextMessage (String content, String weChatUser) {WeChatReplyTextMessage we = new WeChatReplyTextMessage (); we. setMessageType ("text"); we. setFuncFlag ("0"); we. setCreateTime (new Long (new Date (). getTime ()). toString (); we. setContent (content); we. setToUserName (weChatUser); we. setFromUserName ("shanghaiweather"); // TODO your public account No. XStream xstream = new XStream (new DomDriver (); xstream. alias ("xml", WeChatReplyTextMessage. class); xstream. aliasField ("ToUserName", WeChatReplyTextMessage. class, "toUserName"); xstream. aliasField ("FromUserName", WeChatReplyTextMessage. class, "fromUserName"); xstream. aliasField ("CreateTime", WeChatReplyTextMessage. class, "createTime"); xstream. aliasField ("MsgType", WeChatReplyTextMessage. class, "messageType"); xstream. aliasField ("Content", WeChatReplyTextMessage. class, "content"); xstream. aliasField ("FuncFlag", WeChatReplyTextMessage. class, "funcFlag"); String xml = xstream. toXML (we); return xml ;}}
Location recognition is a message that is often used in actual applications. many sellers, especially users, provide users with special product or mall recommendations by understanding their location. The user may send two types of messages:
1. geographic location information
2. road name, landmark building, or mall name
1. geographic location message
Let's take a look at what information the geographic location message contains.
toUser
fromUser
1351776360
location
23.134521
113.358803
20
位置信息
1234567890123456
The information includes the longitude and latitude and the Label location. You can provide services to users based on the location information described in the label. You can also provide your latest product or regional product based on your longitude and latitude information.
First, define the WeChatLocationMessage class based on the geographic location information, and convert the Xml into a WeChatLocationMessage object.
public class WeChatLocationMessage { private String toUserName; private String fromUserName; private String createTime; private String msgType; private String locationx; private String localtiony; private String scale; private String label; private String msgId; public static WeChatLocationMessage getWeChatLocationMessage(String xml){ XStream xstream = new XStream(new DomDriver()); WeChatLocationMessage message = null; xstream.alias("xml", WeChatLocationMessage.class); xstream.aliasField("ToUserName", WeChatLocationMessage.class, "toUserName"); xstream.aliasField("FromUserName", WeChatLocationMessage.class, "fromUserName"); xstream.aliasField("CreateTime", WeChatLocationMessage.class, "createTime"); xstream.aliasField("MsgType", WeChatLocationMessage.class, "msgType"); xstream.aliasField("Location_X", WeChatLocationMessage.class, "locationx"); xstream.aliasField("Location_Y", WeChatLocationMessage.class, "localtiony"); xstream.aliasField("Scale", WeChatLocationMessage.class, "scale"); xstream.aliasField("Label", WeChatLocationMessage.class, "label"); xstream.aliasField("MsgId", WeChatLocationMessage.class, "msgId"); message = (WeChatLocationMessage)xstream.fromXML(xml); return message; } //getter and setter}
This article uses Baidu's Map API to find the nearest bank as an example.
public String getPalace(String query,String lat,String lng) throws ClientProtocolException, IOException{ HttpClient httpClient = new DefaultHttpClient(); String url = palceRequestUrl(query,lat,lng); logger.log(Level.INFO, url); HttpGet httpget = new HttpGet(url); ResponseHandler
responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(httpget, responseHandler); logger.log(Level.INFO,"baidu response:"+responseBody); return responseBody; } public String palceRequestUrl(String query,String lat,String lng) throws UnsupportedEncodingException { String url = WeChatConstant.BASEURL + "place/search?query=" + URLEncoder.encode(query,"UTF-8") + "&key=" + WeChatConstant.MAPKEY +"&location="+lat+","+lng +"&radius=2000"+"&output=" + WeChatConstant.OUTPUTFORMAT; return url; }
Output result
OK
ICBC East Chang 'an Street sub-branch
39.915891
116.41867
1/F, West 3 office building, Oriental Plaza, No. 1, East Chang'an Street, Dongcheng District
A025683c73033c35a21de987
Http://api.map.baidu.com/place/detail? Uid = a025683c73033c35a21de987 & amp; output = html & amp; source = placeapi
Bank, Wangfujing/Dongdan
Next, we will display the latest location information reflected by Baidu Map in text message format to users.
Public static String getWeChatReplyNewsMessageByBaiduPlace (List
PlaceList, double lat, double lng, String userName, int size) {WeChatReplyNewsMessage newsMessage = new WeChatReplyNewsMessage (); List
Items = new ArrayList
(); StringBuffer strBuf = new StringBuffer (); logger. log (Level. INFO, "placeList count =" + placeList. size (); newsMessage. setItems (items); if (placeList. size ()> size) {newsMessage. setArticleCount (size);} else {newsMessage. setArticleCount (placeList. size ();} logger. log (Level. INFO, "article count =" + newsMessage. getArticleCount (); newsMessage. setCreateTime (new Date (). getTime () + ""); newsMessage. setMsgType ("news"); newsMessage. setFuncFlag ("0"); newsMessage. setToUserName (userName); newsMessage. setFromUserName (WeChatConstant. FROMUSERNAME); for (int I = 0; I
2. road name, landmark building, or mall name
The method is to determine the longitude and latitude of the input location information through third-party map information.
This article uses the Baidu Map API to determine the longitude and latitude of the location to be searched.
Once the longitude and latitude are determined, the problem becomes the same as that of the 1st message types. corresponding processing is performed based on the longitude and latitude.
public String getGeoCode(String query) throws ClientProtocolException, IOException{ HttpClient httpClient = new DefaultHttpClient(); String url = geoCodeRequestUrl(query); logger.log(Level.INFO, url); HttpGet httpget = new HttpGet(url); ResponseHandler
responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(httpget, responseHandler); logger.log(Level.INFO,"baidu response:"+responseBody); return responseBody; } public String geoCodeRequestUrl(String query) throws UnsupportedEncodingException{ String url = WeChatConstant.BASEURL + "geocoder?address=" + URLEncoder.encode(query,"UTF-8") + "&key=" + WeChatConstant.MAPKEY + "&output=" + WeChatConstant.OUTPUTFORMAT; return url; }
For more articles related to the public platform development series, please follow the PHP Chinese network!