需要导入maven:
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
1.建立一个微信后台控制层
@RestController
public class WxController {
@Autowired
private MessageDispatcher messageDispatcher
@GetMapping("/wx")
public void login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8")
String signature = request.getParameter("signature")
String timestamp = request.getParameter("timestamp")
String nonce = request.getParameter("nonce")
String echostr = request.getParameter("echostr")
PrintWriter out = null
try {
out = response.getWriter()
if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
out.write(echostr)
}
} catch (IOException e) {
e.printStackTrace()
} finally {
out.close()
}
}
@PostMapping(value = "/wx",produces = "application/xml;charset=utf-8")
public String handler(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8")
/* //将微信请求xml转为map格式,获取所需的参数
Map<String,String> mapJieshou = MessageUtil.xmlToMap(request)
String Content = mapJieshou.get("Content")
Map<String, String> map = WxController.parseXml(request)
String msgType = map.get("MsgType")
if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
return messageDispatcher.processEvent(map)
}else{
return messageDispatcher.processMessage(map)
}
}
/* @PostMapping("/wx")
public void handler(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8")
response.setCharacterEncoding("UTF-8")
PrintWriter out = response.getWriter()
Map<String, String> parseXml = WxController.parseXml(request)
String msgType = parseXml.get("MsgType")
String content = parseXml.get("Content")
String fromusername = parseXml.get("FromUserName")
String tousername = parseXml.get("ToUserName")
System.out.println(msgType)
System.out.println(content)
System.out.println(fromusername)
System.out.println(tousername)
}*/
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
Map<String, String> map = new HashMap<String, String>()
InputStream inputStream = request.getInputStream()
SAXReader reader = new SAXReader()
Document document = reader.read(inputStream)
Element root = document.getRootElement()
List<Element> elementList = root.elements()
for (Element e : elementList)
map.put(e.getName(), e.getText())
inputStream.close()
return map
}
}
2建立后台:
@Component
public class MessageDispatcher {
public static String processMessage(Map<String, String> map) {
String openid = map.get("FromUserName");
String mpid = map.get("ToUserName");
String content = map.get("Content");
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
TextMessage txtmsg = new TextMessage();
txtmsg.setToUserName(openid);
txtmsg.setFromUserName(mpid);
txtmsg.setCreateTime(new Date().getTime());
txtmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
txtmsg.setContent("您输入的是:"+content);
return MessageUtil.textMessageToXml(txtmsg);
}
return null;
}
public String processEvent(Map<String, String> map) {
return "123";
}
}
3建立后台MessageUtil
public class MessageUtil {
/**
* 返回消息类型:文本
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text"
/**
* 返回消息类型:音乐
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music"
/**
* 返回消息类型:图文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news"
/**
* 返回消息类型:图片
*/
public static final String RESP_MESSAGE_TYPE_Image = "image"
/**
* 返回消息类型:语音
*/
public static final String RESP_MESSAGE_TYPE_Voice = "voice"
/**
* 返回消息类型:视频
*/
public static final String RESP_MESSAGE_TYPE_Video = "video"
/**
* 请求消息类型:文本
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text"
/**
* 请求消息类型:图片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image"
/**
* 请求消息类型:链接
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link"
/**
* 请求消息类型:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location"
/**
* 请求消息类型:音频
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice"
/**
* 请求消息类型:视频
*/
public static final String REQ_MESSAGE_TYPE_VIDEO = "video"
/**
* 请求消息类型:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event"
/**
* 事件类型:subscribe(订阅)
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe"
/**
* 事件类型:unsubscribe(取消订阅)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe"
/**
* 事件类型:CLICK(自定义菜单点击事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK"
/**
* 事件类型:VIEW(自定义菜单 URl 视图)
*/
public static final String EVENT_TYPE_VIEW = "VIEW"
/**
* 事件类型:LOCATION(上报地理位置事件)
*/
public static final String EVENT_TYPE_LOCATION = "LOCATION"
/**
* 事件类型:LOCATION(上报地理位置事件)
*/
public static final String EVENT_TYPE_SCAN = "SCAN"
public static String textMessageToXml(TextMessage textMessage) {
xstream.alias("xml", textMessage.getClass())
return xstream.toXML(textMessage)
}
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
boolean cdata = true
@SuppressWarnings("rawtypes")
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)
}
}
}
}
})
/**
* 将微信的请求中参数转成map
* @param request
* @return
*/
public static Map<String,String> xmlToMap(HttpServletRequest request){
Map<String,String> map = new HashMap<String,String>()
SAXReader reader = new SAXReader()
InputStream in = null
try {
in = request.getInputStream()
Document doc = reader.read(in)
Element root = doc.getRootElement()
List<Element> list = root.elements()
for (Element element : list) {
map.put(element.getName(), element.getText())
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}finally{
try {
in.close()
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
return map
}
}
4建立后台CheckUtil
public class CheckUtil {
private static final String token = "wxKeying";
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] str = new String[]{token, timestamp, nonce};
Arrays.sort(str);
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length; i++) {
buffer.append(str[i]);
}
String temp = SHA1.encode(buffer.toString());
return signature.equals(temp);
}
}
5建立SHA1
public class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}