这里接上一篇:服务器配置
既然我们选用了开发者中心,那微信公众平台的自动回复就不得行了,那就自己开发吧。
这就要在服务器配置的URL里面处理了。
一、自动回复处理代码
@RequestMapping(value="/api",method=RequestMethod.POST)
public void initPostAPI(HttpServletRequest request, HttpServletResponse response)
{
String Event = "";
String MsgType = "";
String Content = "";
String strJson = new String();
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
try {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 调用核心业务类接收消息、处理消息
User user = new User();
String respMessage = "";//反馈信息
Map<String, String> map = new HashMap<String, String>();
try {
map = parseXml(request);
} catch (Exception e) {
e.printStackTrace();
}
Event = map.get("Event");
MsgType = map.get("MsgType");
Content = map.get("Content");
System.out.println("Content = " + Content);
System.out.println("MsgType = " + MsgType);
System.out.println("Event = " + Event);
System.out.println("EventKey = " + map.get("EventKey"));
if(Event == null){//Event为null 则为用户输入信息被动回复
//自动回复用户信息
if(MsgType.equals("text")){
strJson = sendMess(map,strJson, Content);
}
}
SendUserMess.sendMess(strJson);
}
public String sendMess(Map map,String strJson,String Content){
//根据用户输入的关键字查询对应响应
AutoReply autoReply = new AutoReply();
autoReply.setKeyName(Content);
List<AutoReply> list = this.replyService.findByKeyname(autoReply);
System.out.println("list size = "+list.size());
//向用户回复消息
if(list.size() != 0){
autoReply = list.get(0);
System.out.println("KeyValue-----"+autoReply.getKeyValue()+"--");
if(!autoReply.getKeyValue().equals("")){
strJson = "{\"touser\" :\""+map.get("FromUserName")+"\",";
strJson += "\"msgtype\":\"text\",";
strJson += "\"text\":{";
strJson += "\"content\":\""+autoReply.getKeyValue()+"\"";
strJson += "}}";
}else if(!autoReply.getGraphic().equals("")){
String newsinfo = "";
String[] strs = autoReply.getGraphic().split(",");
strJson = "{\"touser\" :\""+map.get("FromUserName")+"\",";
strJson += "\"msgtype\":\"news\",";
strJson += "\"news\":";
String news = "{\"articles\": [";
System.out.println(news);
for(String str:strs){
Graphic graphic = graphicService.loadByPK(Integer.valueOf(str));
String url = graphic.getPicurl();
//url = saveUrl + url.substring(24);
newsinfo += "{\"title\":\""+graphic.getTitle()+"\"," +
"\"description\":\""+graphic.getDescription()+"\",\"url\":\""+graphic.getUrl()+"\"," +
"\"picurl\":\""+url+"\""+
"},";
}
news = news + newsinfo.substring(0, (newsinfo.length()-1));
news = news + "]}";
strJson += news;
strJson += "}";
System.out.println("news-------"+news);
}
}else{//如果在数据库中找不到对应回复用户的信息则回复默认消息
autoReply.setKeyName("未知");
List<AutoReply> list_ = this.replyService.findByKeyname(autoReply);
autoReply = list_.get(0);
/*StringBuffer content = new StringBuffer();
content.append("感谢您!").append("\n");
content.append("再次感谢您").append("\n");
content.append("再次再次感谢您");*/
//拼装需要发送的消息
strJson = "{\"touser\" :\""+map.get("FromUserName")+"\",";
strJson += "\"msgtype\":\"text\",";
strJson += "\"text\":{";
strJson += "\"content\":\""+autoReply.getKeyValue()+"\"";
strJson += "}}";
}
return strJson;
}
三、核心代码 SendUserMess
public class SendUserMess {
public static void sendMess(String jsonParam){
String openIdUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
String result = null;
result = String.format(openIdUrl, urlEnodeUTF8(Const.AppId),
urlEnodeUTF8(Const.AppSecrect));
try {
System.out.println("Staring");
// 创建HttpClient实例
DefaultHttpClient httpClient = new DefaultHttpClient ();
// 创建Get方法实例
HttpGet method = new HttpGet(result);
HttpResponse re = httpClient.execute(method);
String resData = EntityUtils.toString(re.getEntity());
method.releaseConnection();
System.out.println("get weixinnumber ..." + resData);
JSONObject obj = JSONObject.fromObject(resData);
if (obj != null) {
String token = obj.getString("access_token");
System.out.println("token = " + token);
//获取ticket
String sendMessUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";
result = String.format(sendMessUrl, token);
httpClient = new DefaultHttpClient();
/*JSONObject jsonParam = new JSONObject();
jsonParam.put("touser", ""+openId+"");
jsonParam.put("msgtype", "text");
jsonParam.put("text", "{'content': '"+respMessage+"'}");*/
System.out.println(jsonParam);
StringEntity entity = new StringEntity(jsonParam,"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
// 创建Get方法实例
HttpPost me = new HttpPost(result);
me.setEntity(entity);
HttpResponse hr = httpClient.execute(me);
String data = EntityUtils.toString(hr.getEntity());
me.releaseConnection();
JSONObject userInfo = JSONObject.fromObject(data);
System.out.println("get backMessage ..." + data);
}
} catch (Exception ex) {
System.out.println("error");
System.out.println(ex.getMessage());
}
}
private static String urlEnodeUTF8(String str){
String result = str;
try {
result = URLEncoder.encode(str,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
这里我用的不是自动回复的哪个接口, 而是用的“发送客服消息”的接口,一样可以达到效果。也可以试下哪个自动回复的接口,反正大体都一样