在校验的时候 微信公众平台向我们发送的是Get的请求,而后接收消息的时候,发送的是Post请求,并且消息的发送和接收和发送都是xml格式,现在看看格式:
<xml>
<ToUserName>< ![CDATA[toUser] ]>ToUserName>
<FromUserName>< ![CDATA[fromUser] ]>FromUserName>
<CreateTime>1348831860CreateTime>
<MsgType>< ![CDATA[text] ]>MsgType>
<Content>< ![CDATA[this is a test] ]>Content>
<MsgId>1234567890123456MsgId>
xml>
<xml>
<ToUserName>< ![CDATA[toUser] ]>ToUserName>
<FromUserName>< ! [CDATA[fromUser] ]>FromUserName>
<CreateTime>1348831860CreateTime>
<MsgType>< ![CDATA[image] ]>MsgType>
<MediaId>< ![CDATA[media_id] ]>MediaId>
<MsgId>1234567890123456MsgId>
xml>
知道了消息的格式,现在我们要做的就是消息的转化
<dependency>
<groupId>dom4jgroupId>
<artifactId>dom4jartifactId>
<version>1.6version>
dependency>
借助dom4j的jar包,我们可以编写方法,将XML格式,转化对Map对象格式,方法实现如下:
public class MessgaeUtils {
/*将xml格式转化为map*/
public Map<String,String> xmlToMap(HttpServletRequest request) throws Exception{
Map<String,String> map=new HashMap<>();
SAXReader reader=new SAXReader();
InputStream inputStream=request.getInputStream();
Document doc=reader.read(inputStream);
Element root=doc.getRootElement();//得到根节点
List<Element> list=root.elements();//根节点下的所有的节点
for(Element e:list){
map.put(e.getName(),e.getText());
}
inputStream.close();
return map;
}
}
消息是实体类:
private String ToUserName;
private String FromUserName;
private Long CreateTime;
private String MsgType;
private String Content;
private String MsgId;
还需要xstream jar将我们的消息内容转变为xml
<dependency>
<groupId>com.thoughtworks.xstreamgroupId>
<artifactId>xstreamartifactId>
<version>1.4version>
dependency>
方法:
/*将我们的消息内容转变为xml*/
public static String objectToXml(Message message){
XStream xStream=new XStream();
xStream.alias("xml", message.getClass());
return xStream.toXML(message);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String str = null;
//将request请求,传到Message工具类的转换方法中,返回接收到的Map对象
try {
Map map = MessgaeUtils.xmlToMap(request);
//从集合中,获取XML各个节点的内容
String ToUserName = map.get("ToUserName");
String FromUserName = map.get("FromUserName");
String CreateTime = map.get("CreateTime");
String MsgType = map.get("MsgType");
String Content = map.get("Content");
String MsgId = map.get("MsgId");
//这里只处理文本消息
if (MsgType.equalsIgnoreCase("text")){
Message message=new Message();
message.setFromUserName(ToUserName);
message.setToUserName(FromUserName);
message.setContent("您发送的消息是text文本消息"+"很帅");
message.setMsgId(MsgId);
message.setMsgType("text");
message.setCreateTime(new Date().getTime());
str=MessgaeUtils.objectToXml(message);
}
System.out.println(str);
}catch (Exception e){
e.printStackTrace();
}
out.print(str);
out.close();
}
参考:
http://www.cnblogs.com/jerehedu/p/6534110.html
<dependencies>
<dependency>
<groupId>dom4jgroupId>
<artifactId>dom4jartifactId>
<version>1.6version>
dependency>
<dependency>
<groupId>com.thoughtworks.xstreamgroupId>
<artifactId>xstreamartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
dependencies>
public class WeiXinServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String str = null;
//将request请求,传到Message工具类的转换方法中,返回接收到的Map对象
try {
Map map = MessgaeUtils.xmlToMap(request);
//从集合中,获取XML各个节点的内容
String ToUserName = map.get("ToUserName");
String FromUserName = map.get("FromUserName");
String CreateTime = map.get("CreateTime");
String MsgType = map.get("MsgType");
String Content = map.get("Content");
String MsgId = map.get("MsgId");
//这里只处理文本消息
if (MsgType.equalsIgnoreCase("text")){
Message message=new Message();
message.setFromUserName(ToUserName);
message.setToUserName(FromUserName);
message.setContent("您发送的消息是text文本消息"+"很帅");
message.setMsgId(MsgId);
message.setMsgType("text");
message.setCreateTime(new Date().getTime());
str=MessgaeUtils.objectToXml(message);
}
System.out.println(str);
}catch (Exception e){
e.printStackTrace();
}
out.print(str);
out.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
System.out.println(request.getMethod().toString());
while (request.getAttributeNames().hasMoreElements()){
System.out.println("1");
request.getAttributeNames().nextElement();
}
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串 由于我使用的是申请的测试账号,并没有随机字符串随意这里的ech是null
String ech = request.getParameter("echostr");
PrintWriter out = response.getWriter();
if (CheckUtil.checkSignature(signature,timestamp,nonce))
System.out.println("校验成功");
out.print(ech);
}
}
<web-app
version="3.0"
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_3_0.xsd">
<servlet>
<servlet-name>bbservlet-name>
<servlet-class>yiche.com.servlet.WeiXinServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>bbservlet-name>
<url-pattern>/ok.dourl-pattern>
servlet-mapping>
web-app>
public class Message {
private String ToUserName;
private String FromUserName;
private Long CreateTime;
private String MsgType;
private String Content;
private String MsgId;
public class MessgaeUtils {
/*将xml格式转化为map*/
public static Map<String,String> xmlToMap(HttpServletRequest request) throws Exception{
Map<String,String> map=new HashMap<>();
SAXReader reader=new SAXReader();
InputStream inputStream=request.getInputStream();
Document doc=reader.read(inputStream);
Element root=doc.getRootElement();//得到根节点
List<Element> list=root.elements();//根节点下的所有的节点
for(Element e:list){
map.put(e.getName(),e.getText());
}
inputStream.close();
return map;
}
/*将我们的消息内容转变为xml*/
public static String objectToXml(Message message){
XStream xStream=new XStream();
xStream.alias("xml", message.getClass());
return xStream.toXML(message);
}
}
public class CheckUtil {
public static final String tooken = "jkjkjkhk"; //开发者自行定义Tooken
//signatrue微信公众平台传过来的的经过加密的签名
public static boolean checkSignature(String signature, String timestamp, String nonce) {
//1.定义数组存放tooken,timestamp,nonce
String[] arr = {tooken, timestamp, nonce};
//2.对数组进行排序
Arrays.sort(arr);
//3.生成字符串
StringBuffer sb = new StringBuffer();
for (String s : arr) {
sb.append(s);
}
//4.sha1加密,网上均有现成代码
String temp = getSha1(sb.toString());
//5.将加密后的字符串,与微信传来的加密签名比较,返回结果
return temp.equals(signature);
}
public static String getSha1(String str){
if(str==null||str.length()==0){
return null;
}
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}