微信例子
时间:2014-10-18 16:39:32
收藏:0
阅读:477
package com.weixin.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //url处可以填写:http://服务器地址/项目名/weixin.do public class TestServlet extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); /** 读取接收到的xml消息 */ StringBuffer sb = new StringBuffer(); InputStream is = request.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); BufferedReader br = new BufferedReader(isr); String s = ""; while ((s = br.readLine()) != null) { sb.append(s); } String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据 String result = ""; /** 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回 */ String echostr = request.getParameter("echostr"); if (echostr != null && echostr.length() > 1) { result = echostr; } else { //正常的微信处理流程 result = new Process().processMag(xml); } try { OutputStream os = response.getOutputStream(); os.write(result.getBytes("UTF-8")); //返回给用户 os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); //即都是调用doGet方法 } }
1.1 在登录微信官方平台之后,开启开发者模式,此时需要我们填写url和token,所谓url就是我们自己服务器的接口,用WechatServlet.java来实现,相关解释已经在注释中说明,代码如上:
1.2 相应的web.xml配置信息如下,在生成WechatServlet.java的同时,可自动生成web.xml中的配置。前面所提到的url处可以填写例如:http;//服务器地址/项目名/wechat.do
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <!-- Weixin servlet --> <servlet> <servlet-name>weixinTest2</servlet-name> <servlet-class>com.weixin.servlet.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>weixinTest2</servlet-name> <url-pattern>/weixin.do</url-pattern> </servlet-mapping> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
package com.weixin.servlet; public class Process { /** * 解析处理xml、获取智能回复结果(通过图灵机器人api接口) * @param xml 接收到的微信数据 * @return 最终的解析结果(xml格式数据) */ public String processMag(String xml){ /** 解析xml数据 */ ReceiveXmlEntity xmlEntity = new ReceiveXmlProcess().getMsgEntity(xml); //用到了反射机制 /** 以文本消息为例,调用图灵机器人api接口,获取回复内容 */ String result = ""; if("text".endsWith(xmlEntity.getMsgType())){//如果是文本信息 //result = new TulingApiProcess().getTulingResult(xmlEntity.getContent()); result = "恭喜你,测试通过了!········"; } /** 此时,如果用户输入的是“你好”,在经过上面的过程之后,result为“你也好”类似的内容 * 因为最终回复给微信的也是xml格式的数据,所有需要将其封装为文本类型返回消息 * */ //即拼接返回的xml result = new FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(), xmlEntity.getToUserName(), result); return result; } }
package com.weixin.servlet; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class ReceiveXmlProcess { /** * 解析微信xml消息 * @param strXml * @return */ public ReceiveXmlEntity getMsgEntity(String strXml){ ReceiveXmlEntity msg = null; try { if (strXml.length() <= 0 || strXml == null) return null; // 将字符串转化为XML文档对象 Document document = DocumentHelper.parseText(strXml); // 获得文档的根节点 Element root = document.getRootElement(); // 遍历根节点下所有子节点 Iterator<?> iter = root.elementIterator(); // 遍历所有结点 msg = new ReceiveXmlEntity(); //利用反射机制,调用set方法 //获取该实体的元类型 Class<?> c = Class.forName("demo.entity.ReceiveXmlEntity"); msg = (ReceiveXmlEntity)c.newInstance();//创建这个实体的对象 while(iter.hasNext()){ Element ele = (Element)iter.next(); //获取set方法中的参数字段(实体类的属性) Field field = c.getDeclaredField(ele.getName()); //获取set方法,field.getType())获取它的参数数据类型 Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType()); //调用set方法 method.invoke(msg, ele.getText()); } } catch (Exception e) { // TODO: handle exception System.out.println("xml 格式异常: "+ strXml); e.printStackTrace(); } return msg; } }
package com.weixin.servlet; import java.util.Date; public class FormatXmlProcess { /** * 封装文字类的返回消息 * @param to * @param from * @param content * @return */ public String formatXmlAnswer(String to, String from, String content) { StringBuffer sb = new StringBuffer(); Date date = new Date(); sb.append("<xml><ToUserName><![CDATA["); sb.append(to); sb.append("]]></ToUserName><FromUserName><![CDATA["); sb.append(from); sb.append("]]></FromUserName><CreateTime>"); sb.append(date.getTime()); sb.append("</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA["); sb.append(content); sb.append("]]></Content><FuncFlag>0</FuncFlag></xml>"); return sb.toString(); } }
调用接口,用之前需要注册
package com.weixin.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.json.JSONObject; //没有用上····ljq public class TulingApiProcess { /** * 调用图灵机器人api接口,获取智能回复内容,解析获取自己所需结果 * @param content * @return */ public String getTulingResult(String content){ /** 此处为图灵api接口,参数key需要自己去注册申请,先以11111111代替 */ /* String apiUrl = "http://www.tuling123.com/openapi/api?key=11111111&info="; String param = ""; try { param = apiUrl+URLEncoder.encode(content,"utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //将参数转为url编码 *//** 发送httpget请求 *//* HttpGet request = new HttpGet(param); String result = ""; try { HttpResponse response = HttpClients.createDefault().execute(request); if(response.getStatusLine().getStatusCode()==200){ result = EntityUtils.toString(response.getEntity()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } *//** 请求失败处理 *//* if(null==result){ return "对不起,你说的话真是太高深了……"; } try { JSONObject json = new JSONObject(result); //以code=100000为例,参考图灵机器人api文档 if(100000==json.getInt("code")){ result = json.getString("text"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ String result = "你好!测试成功了!······"; return result; } }
原文地址:http://down.chinaz.com/try/201408/2492_2.htm
评论(0)