欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java微信二次开发(二) Java微信文本消息接口请求与发送

程序员文章站 2024-02-26 14:35:34
第二篇,做微信文本消息接口请求与发送,具体内容如下 需要导入库:dom4j-1.6.1.jar,xstream-1.3.1.jar 第一步:新建包com.wtz.mes...

第二篇,做微信文本消息接口请求与发送,具体内容如下

需要导入库:dom4j-1.6.1.jar,xstream-1.3.1.jar

第一步:新建包com.wtz.message.response,新建类basemessage.java

package com.wtz.message.response;

/**
 * @author wangtianze qq:864620012
 * @date 2017年4月19日 下午3:12:40
 * <p>version:1.0</p>
 * <p>description:基础消息类</p>
 */
public class basemessage {
 //接收方
 private string tousername;
 //发送方
 private string fromusername;
 //消息的创建时间
 private long createtime;
 //消息类型
 private string msgtype;
 
 public string gettousername() {
 return tousername;
 }
 public void settousername(string tousername) {
 tousername = tousername;
 }
 public string getfromusername() {
 return fromusername;
 }
 public void setfromusername(string fromusername) {
 fromusername = fromusername;
 }
 public long getcreatetime() {
 return createtime;
 }
 public void setcreatetime(long createtime) {
 createtime = createtime;
 }
 public string getmsgtype() {
 return msgtype;
 }
 public void setmsgtype(string msgtype) {
 msgtype = msgtype;
 }
}

第二步:找到包com.wtz.message.response,新建类textmessage.java

package com.wtz.message.response;

/**
 *  @author wangtianze qq:864620012
 * @date 2017年4月19日 下午3:22:33
 * <p>version:1.0</p>
 *  <p>description:文本消息类</p>
 */
public class textmessage extends basemessage{
 //消息内容
 private string content;
 
 public string getcontent() {
  return content;
 }
 public void setcontent(string content) {
  content = content;
 }
}

第三步:找到包com.wtz.util,新建类messageutil.java

package com.wtz.util;

import java.io.ioexception;
import java.io.inputstream;
import java.io.writer;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import javax.servlet.http.httpservletrequest;

import org.dom4j.document;
import org.dom4j.documentexception;
import org.dom4j.element;
import org.dom4j.io.saxreader;

import com.thoughtworks.xstream.xstream;
import com.thoughtworks.xstream.core.util.quickwriter;
import com.thoughtworks.xstream.io.hierarchicalstreamwriter;
import com.thoughtworks.xstream.io.xml.prettyprintwriter;
import com.thoughtworks.xstream.io.xml.xppdriver;
import com.wtz.message.response.textmessage;

/**
 *  @author wangtianze qq:864620012
 * @date 2017年4月19日 下午3:29:58
 * <p>version:1.0</p>
 *  <p>description:消息处理工具类</p>
 */
public class messageutil {
 //定义了消息类型(常量:文本类型)
 public static final string resp_message_type_text = "text";
 
 //从流中解析出每个节点的内容
 public static map<string,string> parsexml(httpservletrequest request) throws ioexception{
  map<string,string> map = new hashmap<string,string>();
  
  //从输入流中获取流对象
  inputstream in = request.getinputstream();
  
  //构建sax阅读器对象
  saxreader reader = new saxreader();
  try {
   //从流中获得文档对象
   document doc = reader.read(in);
   
   //获得根节点
   element root = doc.getrootelement();
   
   //获取根节点下的所有子节点
   list<element> children = root.elements();
   
   for(element e:children){
    //遍历每一个节点,并按照节点名--节点值放入map中
    map.put(e.getname(), e.gettext());
    system.out.println("用户发送的消息xml解析为:" + e.getname() + e.gettext());
   }
   
   //关闭流
   in.close();
   in = null;
  } catch (documentexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  
  return map;
 }
 
 /**
  * 用于扩展节点数据按照<tousername><![cdata[touser]]></tousername>,中间加了cdata段
  */
 private static xstream xstream = new xstream(new xppdriver(){
  public hierarchicalstreamwriter createwriter(writer out){
   return new prettyprintwriter(out){
    boolean cdata = true;
    public void startnode(string name,class clazz){
     super.startnode(name,clazz);
    }
    
    protected void writetext(quickwriter writer,string text){
     if(cdata){
      writer.write("<![cdata[");
      writer.write(text);
      writer.write("]]>");
     }else{
      writer.write(text);
     }
    }
   };
  }
 });
 
 /**
  * 将文本消息转换成xml格式
  */
 public static string messagetoxml(textmessage textmessage){
  xstream.alias("xml",textmessage.getclass());
  string xml = xstream.toxml(textmessage);
  system.out.println("响应所转换的xml:"+xml);
  return xml;
 }
}

第四步:找到包com.wtz.service,新建类processservice.java

package com.wtz.util;

import java.io.ioexception;
import java.util.date;
import java.util.map;

import javax.servlet.http.httpservletrequest;

import com.wtz.message.response.textmessage;

/**
 *  @author wangtianze qq:864620012
 * @date 2017年4月19日 下午8:04:14
 * <p>version:1.0</p>
 *  <p>description:核心服务类</p>
 */
public class processservice {
 public static string dealrequest(httpservletrequest request) throws ioexception{
  //响应的xml串
  string respxml = "";
  
  //要响应的文本内容
  string respcontent = "未知的消息类型";
  map<string,string> requestmap = messageutil.parsexml(request);
  string fromusername = requestmap.get("fromusername");
  string tousername = requestmap.get("tousername");
  string msgtype = requestmap.get("msgtype");
  string content = requestmap.get("content");
  
  system.out.println("用户给公众号发的消息为:" + content);
  
  //构建一条文本消息
  textmessage textmessage = new textmessage();
  textmessage.settousername(fromusername);
  textmessage.setfromusername(tousername);
  textmessage.setcreatetime(new date().gettime());
  textmessage.setmsgtype(messageutil.resp_message_type_text);
  
  if(msgtype.equals(messageutil.resp_message_type_text)){
   respcontent = "王天泽的公众号收到了您的一条文本消息:" + content + ",时间戳是:" + (new date().gettime());
  }
  textmessage.setcontent(respcontent);
  respxml = messageutil.messagetoxml(textmessage);
  
  system.out.println("respxml:"+respxml);
  
  return respxml;
 }
}

第五步:找到包com.wtz.service下的loginservlet类,重写dopost方法

package com.wtz.service;

import java.io.ioexception;
import java.io.printwriter;

import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import com.wtz.util.messageutil;
import com.wtz.util.processservice;
import com.wtz.util.validationutil;

/**
 *  @author wangtianze qq:864620012
 * @date 2017年4月17日 下午8:11:32
 * <p>version:1.0</p>
 *  <p>description:微信请求验证类</p>
 */
public class loginservlet extends httpservlet {

 @override
 protected void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  system.out.println("get请求。。。。。。");
  
  //1.获得微信签名的加密字符串
  string signature = request.getparameter("signature");
  
  //2.获得时间戳信息
  string timestamp = request.getparameter("timestamp");
   
  //3.获得随机数
  string nonce = request.getparameter("nonce");
  
  //4.获得随机字符串
  string echostr = request.getparameter("echostr");
  
  system.out.println("获得微信签名的加密字符串:"+signature);
  system.out.println("获得时间戳信息:"+timestamp);
  system.out.println("获得随机数:"+nonce);
  system.out.println("获得随机字符串:"+echostr);
  
  printwriter out = response.getwriter();
  
  //验证请求确认成功原样返回echostr参数内容,则接入生效,成为开发者成功,否则失败
  if(validationutil.checksignature(signature, timestamp, nonce)){
   out.print(echostr);
  }
  
  out.close();
  out = null;
 }

 /**
  * 接受微信服务器发过来的xml数据包(通过post请求发送过来的)
  */
 @override
 protected void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  
  request.setcharacterencoding("utf-8");
  response.setcharacterencoding("utf-8");
  
  //获取微信加密的签名字符串
  string signature = request.getparameter("signature");
  
  //获取时间戳
  string timestamp = request.getparameter("timestamp");
  
  //获取随机数
  string nonce = request.getparameter("nonce");
  
  printwriter out = response.getwriter();
  
  if(validationutil.checksignature(signature,timestamp,nonce)){
   string respxml = "";
   try {
    respxml = processservice.dealrequest(request);
   } catch (exception e) {
    // todo auto-generated catch block
    e.printstacktrace();
   }
   out.print(respxml);
  }
  out.close();
  out = null;
 }
}

完成微信文本消息接口请求与发送。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。