100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > JAVA微信公众号开发之自动回复消息与图片

JAVA微信公众号开发之自动回复消息与图片

时间:2023-11-10 02:00:20

相关推荐

JAVA微信公众号开发之自动回复消息与图片

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

回复文本消息

回复图片消息

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

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

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.jarInputStream 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.jarxstream.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.jarxstream.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("\r\n");sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");sb.append("Content-Type:application/octet-stream\r\n\r\n");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 = ("\r\n--" + BOUNDARY + "--\r\n").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_tokenString 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 blocke.printStackTrace();}}

最近在整理一些资源工具,放在网站分享

欢迎关注公众号:麻雀唯伊 , 不定时更新资源文章,生活优惠,或许有你想看的

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。