Java微信公众平台开发(8) 多媒体消息回复
程序员文章站
2024-02-27 19:13:09
之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复【普通消息类型消息】,这里将讲述多媒体消息的回复方法,【多媒体消息】包含回复图片消息/回复语音消...
之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复【普通消息类型消息】,这里将讲述多媒体消息的回复方法,【多媒体消息】包含回复图片消息/回复语音消息/回复视频消息/回复音乐消息,这里以图片消息的回复为例进行讲解!
还记得之前将消息分类的标准就是一种是不需要上传多媒体资源到腾讯服务器的而另外一种是需要的,所以在这里我们所需要做的第一步就是上传资源到腾讯服务器,这里我们调用【素材管理】接口(后面将会有专门的章节讲述)进行图片的上传,同样的这个接口可以提供我们对语音、视频、音乐等消息的管理,这里以图片为例(文档地址: )。在文档中我们可以发现这里上传的方式是模拟表单的方式上传,然后返回给我们我们需要在回复消息中需要用到的参数:media_id!
(一)素材接口图片上传
按照之前我们的约定将接口请求的url写入到配置文件interface_url.properties中:
#获取token的url tokenurl=https://api.weixin.qq.com/cgi-bin/token #永久多媒体文件上传url mediaurl=http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=
然后我在这里写了一个模拟表单上传的工具类httppostuploadutil.java,如下:
package com.cuiyongzhi.wechat.util; import java.io.bufferedreader; import java.io.datainputstream; import java.io.dataoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.inputstreamreader; import java.io.outputstream; import java.net.httpurlconnection; import java.net.url; import java.util.iterator; import java.util.map; import javax.activation.mimetypesfiletypemap; import com.cuiyongzhi.web.util.globalconstants; /** * classname: httppostuploadutil * @description: 多媒体上传 * @author dapengniao * @date 2016年3月14日 上午11:56:55 */ public class httppostuploadutil { public string urlstr; public httppostuploadutil(){ urlstr = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+globalconstants.getinterfaceurl("access_token")+"&type=image"; } /** * 上传图片 * * @param urlstr * @param textmap * @param filemap * @return */ @suppresswarnings("rawtypes") public string formupload(map<string, string> textmap, map<string, string> filemap) { string res = ""; httpurlconnection conn = null; string boundary = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符 try { url url = new url(urlstr); conn = (httpurlconnection) url.openconnection(); conn.setconnecttimeout(5000); conn.setreadtimeout(30000); conn.setdooutput(true); conn.setdoinput(true); conn.setusecaches(false); conn.setrequestmethod("post"); conn.setrequestproperty("connection", "keep-alive"); conn .setrequestproperty("user-agent", "mozilla/5.0 (windows; u; windows nt 6.1; zh-cn; rv:1.9.2.6)"); conn.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary); outputstream out = new dataoutputstream(conn.getoutputstream()); // text if (textmap != null) { stringbuffer strbuf = new stringbuffer(); iterator<?> iter = textmap.entryset().iterator(); while (iter.hasnext()) { map.entry entry = (map.entry) iter.next(); string inputname = (string) entry.getkey(); string inputvalue = (string) entry.getvalue(); if (inputvalue == null) { continue; } strbuf.append("\r\n").append("--").append(boundary).append( "\r\n"); strbuf.append("content-disposition: form-data; name=\"" + inputname + "\"\r\n\r\n"); strbuf.append(inputvalue); } out.write(strbuf.tostring().getbytes()); } // file if (filemap != null) { iterator<?> iter = filemap.entryset().iterator(); while (iter.hasnext()) { map.entry entry = (map.entry) iter.next(); string inputname = (string) entry.getkey(); string inputvalue = (string) entry.getvalue(); if (inputvalue == null) { continue; } file file = new file(inputvalue); string filename = file.getname(); string contenttype = new mimetypesfiletypemap() .getcontenttype(file); if (filename.endswith(".jpg")) { contenttype = "image/jpg"; } if (contenttype == null || contenttype.equals("")) { contenttype = "application/octet-stream"; } stringbuffer strbuf = new stringbuffer(); strbuf.append("\r\n").append("--").append(boundary).append( "\r\n"); strbuf.append("content-disposition: form-data; name=\"" + inputname + "\"; filename=\"" + filename + "\"\r\n"); strbuf.append("content-type:" + contenttype + "\r\n\r\n"); out.write(strbuf.tostring().getbytes()); 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[] enddata = ("\r\n--" + boundary + "--\r\n").getbytes(); out.write(enddata); out.flush(); out.close(); // 读取返回数据 stringbuffer strbuf = new stringbuffer(); bufferedreader reader = new bufferedreader(new inputstreamreader( conn.getinputstream())); string line = null; while ((line = reader.readline()) != null) { strbuf.append(line).append("\n"); } res = strbuf.tostring(); reader.close(); reader = null; } catch (exception e) { system.out.println("发送post请求出错。" + urlstr); e.printstacktrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } return res; } }
我们将工具类写好之后就需要在我们消息回复中加入对应的响应代码,这里为了测试我将响应代码加在【关注事件】中!
(二)图片回复
这里我们需要修改的是我们的【事件消息业务分发器】的代码,这里我们将我们的回复加在【关注事件】中,简单代码如下:
string openid = map.get("fromusername"); // 用户openid string mpid = map.get("tousername"); // 公众号原始id imagemessage imgmsg = new imagemessage(); imgmsg.settousername(openid); imgmsg.setfromusername(mpid); imgmsg.setcreatetime(new date().gettime()); imgmsg.setmsgtype(messageutil.resp_message_type_image); if (map.get("event").equals(messageutil.event_type_subscribe)) { // 关注事件 system.out.println("==============这是关注事件!"); image img = new image(); httppostuploadutil util=new httppostuploadutil(); string filepath="h:\\1.jpg"; map<string, string> textmap = new hashmap<string, string>(); textmap.put("name", "testname"); map<string, string> filemap = new hashmap<string, string>(); filemap.put("userfile", filepath); string mediaidrs = util.formupload(textmap, filemap); system.out.println(mediaidrs); string mediaid=jsonobject.fromobject(mediaidrs).getstring("media_id"); img.setmediaid(mediaid); imgmsg.setimage(img); return messageutil.imagemessagetoxml(imgmsg); }
到这里代码基本就已经完成整个的图片消息回复的内容,同样的不论是语音回复、视频回复等流程都是一样的,所以其他的就不在做过多的讲述了,最后的大致效果如下:
正常的消息回复的内容我们就讲述的差不多了,下一篇我们讲述基于消息回复的一些应用【关键字回复及超链接回复】的实现,感谢你的翻阅,如有疑问可以留言讨论!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。