作者: whooyun发表于: 2018-06-05 11:31
网上很多解决办法都是说设置request,response设置成UTF-8就行
//微信服务器POST消息时用的是UTF-8编码,在接收时也要用同样的编码,否则中文会乱码;
request.setCharacterEncoding("UTF-8");
//在响应消息(回复消息给用户)时,也将编码方式设置为UTF-8,原理同上;
response.setCharacterEncoding("UTF-8");
其实都是扯淡,下面我直接贴代码:
/**
* 消息自动回复方法
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/wechat/responseMsg")
public void responseMsg(@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "echoStr", required = false) String echoStr,
@RequestBody(required = false) String content,
HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
PrintWriter out = response.getWriter();
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
//微信服务器POST消息时用的是UTF-8编码,在接收时也要用同样的编码,否则中文会乱码;
request.setCharacterEncoding("UTF-8");
//在响应消息(回复消息给用户)时,也将编码方式设置为UTF-8,原理同上;
response.setCharacterEncoding("UTF-8");
boolean isGet = request.getMethod().toLowerCase().equals("get");
String openId = request.getParameter("openid");
try {
//微信服务器验证时使用get方法请求的
if (isGet) {
// 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
if (SignUtils.checkSignature(signature, timestamp, nonce)) {
out.print(echoStr);
}
}
if (!StringUtils.isEmpty(content)) {
String xmlMsgType = XmlUtils.getElementTextByName(content, "MsgType");
if (WechatConstants.XmlMsgType.TEXT.equals(xmlMsgType)) {
//回复文本消息
} else if (WechatConstants.XmlMsgType.IMAGE.equals(xmlMsgType)) {
//处理用户回复图片事件
} else if (WechatConstants.XmlMsgType.EVENT.equals(xmlMsgType)) {
//处理用户关注/取消关注公众号事件
String wechatEventType = XmlUtils.getElementTextByName(content, "Event");
if (WechatConstants.WechatEventType.SUBSCRIBE.equals(wechatEventType)) {
//处理用户关注微信公众号
} else if (WechatConstants.WechatEventType.UNSUBSCRIBE.equals(wechatEventType)) {
// 用户取消关注公众号事件
} else if (WechatConstants.WechatEventType.CLICK.equals(wechatEventType)) {
String eventKey = XmlUtils.getElementTextByName(content, "EventKey");
if ("V2005_QMYH".equals(eventKey)) {
} else if ("V1003_QMYH".equals(eventKey)) {
}
// 微信底部菜单点击事件
} else if (WechatConstants.WechatEventType.VIEW.equals(wechatEventType)) {
//点击微信底部菜单访问某个访问事件
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
已验证,此种访问真无用。
第二种方法,设置每次输出的汉字字符串编码,这个方法真的有用
byte[] byte = null;//编码
try {
byte = responseText.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
result = new String(byte, "iso8859-1");
//result 是字符串类型,存的就是你最终输出的汉字,解码
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}