Java微信公众平台开发(8) 多媒体消息回复
作者:dapengniao 发布时间:2023-02-19 19:57:42
之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复【普通消息类型消息】,这里将讲述多媒体消息的回复方法,【多媒体消息】包含回复图片消息/回复语音消息/回复视频消息/回复音乐消息,这里以图片消息的回复为例进行讲解!
还记得之前将消息分类的标准就是一种是不需要上传多媒体资源到腾讯服务器的而另外一种是需要的,所以在这里我们所需要做的第一步就是上传资源到腾讯服务器,这里我们调用【素材管理】接口(后面将会有专门的章节讲述)进行图片的上传,同样的这个接口可以提供我们对语音、视频、音乐等消息的管理,这里以图片为例(文档地址:http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html )。在文档中我们可以发现这里上传的方式是模拟表单的方式上传,然后返回给我们我们需要在回复消息中需要用到的参数: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);
}
到这里代码基本就已经完成整个的图片消息回复的内容,同样的不论是语音回复、视频回复等流程都是一样的,所以其他的就不在做过多的讲述了,最后的大致效果如下:
正常的消息回复的内容我们就讲述的差不多了,下一篇我们讲述基于消息回复的一些应用【关键字回复及超链接回复】的实现,感谢你的翻阅,如有疑问可以留言讨论!
猜你喜欢
- 现在很多网站都有注册登录的页面,为了更好的满足用户体验和网站的安全性,很多网站都采用动态生成的图形码或者是附加码进行验证,下面把生成验证码的
- 一、作用和区别 break的作用是跳出当前循环块(for、while、do while)或程序块(switch)。在循环块中的作用
- 本文是vhr系列的第十二篇,项目地址 https://github.com/lenve/vhr邮件发送也是一个老生常谈的问题了,代码虽然简单
- hadoop做的一个简单grep程序,可从文档中提取包含某些字符串的行/* * 一个简单grep程序,可从文档中提取包含莫些字符串
- 此篇文章内容仅限于 描述 thy3.0 自定义标签的说明,所以你在看之前,请先会使用它。直奔主题,以下代码是如何引用 第三方标签的。说明:
- 最近碰到这么个恶心的问题问题:有个arr文件被放到Module A中引用,现在Module B又依赖了Module A,则在编译过程中会发生
- 昨天写了一篇Redis布隆过滤器相关的命令的文章,今天来说一说springboot中如何简单在代码中使用布隆过滤器吧。目前市面上也有好几种实
- 前言前面一篇我们介绍了使用 shared_preferences实现简单的键值对存储,然而我们还会面临更为复杂的本地存储。比如资讯类 App
- 多选和单选的不同之处单选的时候,选中一个就可以直接把结果返回,因此本身底部弹窗无需状态管理。但到多选的时候,需要知道当前选中的选项,有选项被
- 本文实例为大家分享了java实现文件下载的具体代码,供大家参考,具体内容如下public HttpServletResponse downl
- 委托的Invoke方法用来进行同步调用。同步调用也可以叫阻塞调用,它将阻塞当前线程,然后执行调用,调用完毕后再继续向下进行。同步调用的例子:
- Struts2是流行和成熟的基于MVC设计模式的Web应用程序框架。 Struts2不只是Struts1下一个版本,它是一个完全重写的Str
- Java的一个重要特性就是通过垃圾收集器(GC)自动管理内存的回收,而不需要程序员自己来释放内存。理论上Java中所有不会再被利用的对象所占
- 一、Filter(过滤器)Filter接口定义在javax.servlet包中,是Servlet规范定义的,作用于Request/Respo
- 1.可能是缓存导致的。解决方法:清除缓存!2.全局编译可能项目依赖别的模块,别的模块修改未进行编译,这时须先对依赖模块进行编译补充知识:ID
- HashMap类1、HashMap类概述HashMap是 Map 接口使用频率最高的实现类,允许使用null键和null值,与HashSet
- 前言在框架中经常会会用到method.invoke()方法,用来执行某个的对象的目标方法。以前写代码用到反射时,总是获取先获取Method,
- 近日于LeetCode看题遇1114 按序打印,获悉一解法使用了Semaphore,顺势研究,记心得于此。此解视Semaphore为锁,以保
- 缘起经过前面三章的入门,我们大概了解了Mybatis的主线逻辑是什么样子的,在本章中,我们将正式进入Mybatis的源码海洋。Mybatis
- utf-8转unicode public static String utf8ToUnicode(String inStr) {