微信开发接收普通消息、自动回复

消息类型有:
1 文本消息
2 图片消息
3 语音消息
4 视频消息
5 小视频消息
6 地理位置消息
7 链接消息
文本消息

ServletInputStream is = request.getInputStream();// 获得
                                                                // 输入流(微信端接收的消息报文)
            SAXReader reader = new SAXReader();// 读入数据
            Document doc;// dom4j.doucment文件结构,解析XML
            doc = reader.read(is);
            TextRsp rep = new TextRsp();// 创建一个文本消息的对象
            Element rootElement = doc.getRootElement();// rootElement( 
            // elements(。。。)
            List elements = rootElement.elements();

            // 交换FromUserName和ToUserName的内容
            for (Element element : elements) {
                System.out.println(element.getName());
                System.out.println(element.getStringValue());
                if (element.getName().equals("ToUserName")) {
                    rep.setFromUserName(element.getStringValue());
                }
                if (element.getName().equals("FromUserName")) {
                    rep.setToUserName(element.getStringValue());
                }

            }
            rep.setCreateTime(System.currentTimeMillis() + "");
            rep.setMsgType("text");//设置消息类型

发送消息
rep.setContent(“0000”);
String textMessageToXml = textMessageToXml(rep);//回复的消息转化为xml

    respextMessageToXml);//回复消息
    转化为XML需要导入xstrseam 的包
    public static String textMessageToXml(Object rsp) {
    xstrseam.alias("xml", rsp.getClass());
    return xstrseam.toXML(rsp);
}n xstrseam.toXML(rsp);
}


public static XStream xstrseam = new XStream(new XppDriver() {

    public HierarchicalStreamWriter createWriter(Writer out) {
        return new PrettyPrintWriter(out) {
            boolean cdata = true;

            protected void writeText(QuickWriter writer, String text) {
                if (cdata) {
                    writer.write("");
                } else {
                    writer.write(text);
                }
            }
        };
    }

});

自动回复消息,连接图灵机器人从网上获取urll 和key
private static String urll = “http://www.tuling123.com/openapi/api“;
private static String key = “513e5227401d8333484deafec4d3ce73”;
private static String readLine;
String encode = URLEncoder.encode(recContent, “UTF-8”);
String addr = urll + “?key=” + key + “&info=” + encode;
URL url = new URL(addr);
URLConnection openConnection = url.openConnection();
openConnection.connect();
InputStream in = openConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, “utf-8”));
readLine = br.readLine();
readLine = jsonToObject(readLine);readLine返回的是json字符串需要将就送字符串的content获取。。。。创建一个ContentBean类里面有code属性和text属性
public static String jsonToObject(String readLine) {

    Gson gson = new Gson();
    Content fromJson = gson.fromJson(readLine, Content.class);//将获得的json转化为Content对象


    return fromJson.getText();

你可能感兴趣的:(微信开发接收普通消息、自动回复)