微信接口校验
1、Servlet
package com.itmayiedu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itmayiedu.entity.TestMesgEntity;
import com.itmayiedu.utils.CheCkeUtils;
import com.itmayiedu.utils.MesAgeUtils;
/**
* Servlet implementation class WeiXinServlet
*/
@WebServlet("/WeiXinServlet")
public class WeiXinServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WeiXinServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* get请求,微信接口校验
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
PrintWriter writer = response.getWriter();
if (CheCkeUtils.cheCkeSignature(signature, timestamp, nonce)) {
writer.write(echostr);
}
}
/**
* post请求,发送文本消息
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 接受用户发送消息1、用户发送內容 微信会推送xml消息 将XML转换成map
PrintWriter writer = response.getWriter();
try {
Map<String, String> xmlMap = MesAgeUtils.toXmlMap(request);
System.out.println("xmlMap:" + xmlMap);
String msgType = xmlMap.get("MsgType");
String result = null;
if (msgType.equals("text")) {
TestMesgEntity testMesgEntity = new TestMesgEntity();
testMesgEntity.setToUserName(xmlMap.get("FromUserName"));
testMesgEntity.setFromUserName(xmlMap.get("ToUserName"));
testMesgEntity.setCreateTime(System.currentTimeMillis() + "");
testMesgEntity.setMsgType("text");
String userContent=xmlMap.get("Content");
String content = null;
if(userContent.equals("上海天气")){
content="上海天气,今天最低温度17度,最高温度22度。多云";
}else if(userContent.equals("蚂蚁课堂")){
content="蚂蚁课堂专为喜欢IT爱好者提供免费的教学视频网站 www.itmayiedu.com";
}else{
content="您消息我们已经收到,我们会及时处理的的!谢谢您对蚂蚁课堂的关心。";
}
testMesgEntity.setContent(content);
result = MesAgeUtils.testMessageToXml(testMesgEntity);
}
System.out.println("result:");
System.out.println("result:" + result);
writer.write(result);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
writer.close();
}
}
}
2、工具类:
package com.itmayiedu.utils;
import java.security.MessageDigest;
import java.util.Arrays;
public class CheCkeUtils {
private static final String token = "ding";
public static boolean cheCkeSignature(String signature, String timestamp, String nonce)
{
String[] arr = new String[] { token, timestamp, nonce };
// 排序
Arrays.sort(arr);
StringBuffer sf = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sf.append(arr[i]);
}
// sha1验证
String temp = getSha1(sf.toString());
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;
}
}
}
package com.itmayiedu.utils;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.itmayiedu.entity.TestMesgEntity;
import com.thoughtworks.xstream.XStream;
public class MesAgeUtils {
/**
* 将xml转换成map
*
* @param request
* @return
* @throws IOException
* @throws DocumentException
*/
public static Map<String, String> toXmlMap(HttpServletRequest request) throws IOException, DocumentException {
Map<String, String> map = new HashMap<String, String>();
SAXReader saxReader = new SAXReader();
// 获取用户输入的文件流
ServletInputStream inputStream = request.getInputStream();
// 将文件流转换成map
Document doc = saxReader.read(inputStream);
Element root = doc.getRootElement();
List<Element> elements = root.elements();
for (Element element : elements) {
map.put(element.getName(), element.getText());
}
return map;
}
/**
* 将实体类转换成map
*
* @param testMesgEntity
* @return
*/
public static String testMessageToXml(TestMesgEntity testMesgEntity) {
XStream xStream = new XStream();
xStream.alias("xml", testMesgEntity.getClass());
return xStream.toXML(testMesgEntity);
}
}
实体类:
package com.itmayiedu.entity;
public class TestMesgEntity {
private String ToUserName;
private String FromUserName;
private String CreateTime;
private String MsgType;
private String Content;
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 String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}