微信公众号自动回复

首先,应该建立一个消息与图片的实体,看一下微信公众号的文档:

 原网址

回复文本消息
<xml>

<ToUserName><![CDATA[toUser]]></ToUserName>

<FromUserName><![CDATA[fromUser]]></FromUserName>

<CreateTime>12345678</CreateTime>

<MsgType><![CDATA[text]]></MsgType>

<Content><![CDATA[你好]]></Content>

</xml>

参数 是否必须 描述
ToUserName 是 接收方帐号(收到的OpenID)
FromUserName 是 开发者微信号
CreateTime 是 消息创建时间 (整型)
MsgType 是 text
Content 是 回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)
回复图片消息
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[media_id]]></MediaId>
</Image>
</xml>
 

参数 是否必须 说明
ToUserName 是 接收方帐号(收到的OpenID)
FromUserName 是 开发者微信号
CreateTime 是 消息创建时间 (整型)
MsgType 是 image
MediaId 是
通过素材管理中的接口上传多媒体文件,得到的id。

之后组装实体,用户发来消息或者事件时候给微信服务器发送请求,服务器把消息返回给在公众号配置的服务器域名处,然后再进行逻辑判断,给微信服务器返回消息,发给用户。

下面给出一般的消息类型:

        public static final String MESSAGE_SCAN="SCAN";//未关注公众号扫描二维码
public static final String MESSAGE_TEXT="text";//文本
public static final String MESSAGE_IMAGE="image";//图片
public static final String MESSAGE_VOICE="voice";//语音
public static final String MESSAGE_VIDEO="video";//视频
public static final String MESSAGE_LINK="link";//连接
public static final String MESSAGE_LOCATION="location";//地理位置事件
public static final String MESSAGE_EVENT="event";//事件
public static final String MESSAGE_SUBSCRIBE="subscribe";//关注
public static final String MESSAGE_UNSUBSCRIBE="unsubscribe";//取消关注
public static final String MESSAGE_CLICK="CLICK";//点击
public static final String MESSAGE_VIEW="VIEW";//t跳转链接url

需要注意的是,发送图片需要先把图片上传到微信服务器获取MediaId,才能发给用户。

/**
* xml转为map集合
* @MethodName:xmlToMap
*@author:maliran
*@ReturnType:Map<String,String>
*@param req
*@return
*@throws IOException
*@throws DocumentException
*/
public static Map<String,String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException{

Map<String,String> map = new HashMap<String,String>();
SAXReader reader = new SAXReader();//log4j.jar
InputStream ins = req.getInputStream();
Document doc = reader.read(ins);
Element root = doc.getRootElement();
List<Element> list = root.elements();
for(Element e:list){
map.put(e.getName(), e.getText());
}
ins.close();
return map;
}
/**
* 文本转换为xml
* @MethodName:textMessageToXml
*@author:maliran
*@ReturnType:String
*@param textMessage
*@return
*/
public static String textMessageToXml(TextMessage textMessage){

XStream xstream = new XStream();//xstream.jar,xmlpull.jar
xstream.alias("xml", textMessage.getClass());//置换根节点
System.out.println(xstream.toXML(textMessage));
return xstream.toXML(textMessage);

}
/**
* 图片转成xml
* @MethodName:textMessageToXml
*@author:maliran
*@ReturnType:String
*@param textMessage
*@return
*/
public static String imageMessageToXml(ImageMessage imageMessage){

XStream xstream = new XStream();//xstream.jar,xmlpull.jar
xstream.alias("xml", imageMessage.getClass());//置换根节点
//System.out.println(xstream.toXML(imageMessage));
return xstream.toXML(imageMessage);

}

/**
* 组装图片xml
* @MethodName:initImageMessage
*@author:maliran
*@ReturnType:String
*@param MediaId
*@param toUserName
*@param fromUserName
*@return
*/
public static String initImageMessage(String MediaId,String toUserName,String fromUserName){
String message = null;
Image image = new Image();
ImageMessage imageMessage = new ImageMessage();
image.setMediaId(MediaId);
imageMessage.setFromUserName(toUserName);
imageMessage.setToUserName(fromUserName);
imageMessage.setCreateTime(new Date().toString());
imageMessage.setImage(image);
imageMessage.setMsgType(MESSAGE_IMAGE);
message = imageMessageToXml(imageMessage);
return message;
}
public static String initTextMessage(String content,String toUserName,String fromUserName){
String message = null;
TextMessage textMessage = new TextMessage();
textMessage.setFromUserName(toUserName);
textMessage.setToUserName(fromUserName);
textMessage.setCreateTime(new Date().toString());
textMessage.setContent(content);
textMessage.setMsgType(MESSAGE_TEXT);
message = textMessageToXml(textMessage);
return message;
}
/**
* 上传本地文件到微信获取mediaId
*/

public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}

String url = ConfigUtil.UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);

URL urlObj = new URL(url);
//连接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

//设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");

//设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append(" ");
sb.append("Content-Disposition: form-data;name="file";filename="" + file.getName() + "" ");
sb.append("Content-Type:application/octet-stream ");

byte[] head = sb.toString().getBytes("utf-8");

//获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
//输出表头
out.write(head);

//文件正文部分
//把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();

//结尾部分
byte[] foot = (" --" + BOUNDARY + "-- ").getBytes("utf-8");//定义最后数据分隔线

out.write(foot);

out.flush();
out.close();

StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String result = null;
try {
//定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}

JSONObject jsonObj = JSONObject.fromObject(result);
System.out.println(jsonObj);
String typeName = "media_id";
if(!"image".equals(type)){
typeName = type + "_media_id";
}
String mediaId = jsonObj.getString(typeName);
return mediaId;
}
 

public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String serverPath="";
serverPath = req.getServletContext().getRealPath("/").replace("\", "/");
//Servlet初始化时执行,如果上传文件目录不存在则自动创建
if(!new File(serverPath+"qrimage").isDirectory()){
new File(serverPath+"qrimage").mkdirs();
}
PrintWriter out = resp.getWriter();

//String openId = GetCookie.getCookie(req,resp);
Map<String, String> map;
try {
map = MessageUtil.xmlToMap(req);
String fromUserName = map.get("FromUserName");
System.out.println(fromUserName);
String toUserName = map.get("ToUserName");

String msgType = map.get("MsgType");
//String content = map.get("Content");

String message = "";
if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
System.out.println("事件");
String eventType = map.get("Event");
System.out.println(eventType);
String eventKey = map.get("EventKey");
System.out.println(map.get("EventKey"));
if(MessageUtil.MESSAGE_CLICK.equals(eventType)){
String key = map.get("EventKey");
if(key.equals("1")){
String filePath = serverPath+"qrimage"+"\"+fromUserName+".jpg";
//String url = "WebContent/qrimage/"+fromUserName+".jpg";
String ticket = wxQRCodeService.createForeverStrTicket(fromUserName);

//System.out.println(url);
//获取access_token
String content = "123456";
String mediaId = MyImageUtil.upload(filePath, accessToken,MessageUtil.MESSAGE_IMAGE);
String imageMessage = MessageUtil.initImageMessage(mediaId, toUserName, fromUserName);

System.out.println(imageMessage);

out.print(imageMessage);
out.close();


}}

}else{
return;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
 

原文地址:https://www.cnblogs.com/zpbk/p/12699653.html