微信公众号开发数据交互消息的接受与响应
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号开发数据交互消息的接受与响应相关的知识,希望对你有一定的参考价值。
微信公众号开发:
->创建servlet 继承httpServlet
->doGet方法里边验证:
protected void doGet(HttpServletRequest req,HttpServletResponse resp){
//获取参数
String signature = req.getParameter(“signature”);
String timestamp = req.getParameter(“timestamp”);
String nonce = req.getParameter(“nonce”);
String echostr = req.getParameter(echostr);
PrintWriter out = resp.getWriter();
If(CheckUtil.checkSignature(signature,timestamp,nonce))
Out.print(echostr);
}
->校验工具类:
Private static final String token = “imooc”;
Public static Boolean checkSignature(String signature,String timestamp,String nonce){
String[] arr = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(arr);
//生成字符串
StringBuffer content = new StringBuffer();
for(int i=0;i<arr.length;i++){
content.append(arr[i]);
}
//sha1加密
String temp = getSha1(content.toString);
Return temp.equals(signature);
}
Public static String getSha1(String str){}//网上下载
->Web.xml中配置servlet
<servlet>
<servlet-name>weixinServlet</servlet-name>
<servlet-class>com.imooc.servlet.WeixinServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wexinServlet</servlet-name>
<url-pattern>/wx.do<url-pattern>
</servlet-mapping>
通过映射工具将项目映射到公网上,然后在公网上访问servlet
->消息的接受与响应
文本消息:
Servlet的doPost方法中:
req.setCharacterEncoding(“UTF-8”);
resp.setCharacterEncoding(“UTF-8”);
PrintWriter out = resp.getWriter();
Try{
Map<String,String>map = MessageUtil.xmlToMap(req);
String fromUserName = map.get(“FromUserName”);
String toUserName = map.get(ToUserName);
String msgType = map.get(“MsgType”);
String content = map.get(“Content”);
String message = null;
if(“text”.equals(msgType)){
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);
}
out.print(message);
}catch(DocumentException e){
e.printStackTrace();
}finally{
out.close();
}
以下为工具类:
Xml数据转换为集合的方法://需要添加dom4j jar包
Public class MessageUtil{
Public static Map<String,String>xmlToMap(HttpServletRequest request){
Map<String,String>map = new HashMap<String,String>();
SAXReader reader = new SAXReader();
InputStream ins = request.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;
}
将text类型的消息转换为xml //需添加xstream jar包
Public static String textMessageToXml(TextMessage textMessage){
XStream xstream = new XStream();
Xstream.alias(“xml”,textMessage.getClass());
Xstream.toXML(textMessage);
}
}
创建TextMessage类
添加6个文本对象的属性
以上是关于微信公众号开发数据交互消息的接受与响应的主要内容,如果未能解决你的问题,请参考以下文章