转自:http://www.cuiyongzhi.com/post/46.html

之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复【普通消息类型消息】,这里将讲述多媒体消息的回复方法,【多媒体消息】包含回复图片消息/回复语音消息/回复视频消息/回复音乐消息,这里以图片消息的回复为例进行讲解!

还记得之前将消息分类的标准就是一种是不需要上传多媒体资源到腾讯服务器的而另外一种是需要的,所以在这里我们所需要做的第一步就是上传资源到腾讯服务器,这里我们调用【素材管理】接口(后面将会有专门的章节讲述)进行图片的上传,同样的这个接口可以提供我们对语音、视频、音乐等消息的管理,这里以图片为例(文档地址:http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html  )。在文档中我们可以发现这里上传的方式是模拟表单的方式上传,然后返回给我们我们需要在回复消息中需要用到的参数:media_id!

(一)素材接口图片上传

按照之前我们的约定将接口请求的url写入到配置文件interface_url.properties中:

1
2
3
4
#获取token的url
#永久多媒体文件上传url

然后我在这里写了一个模拟表单上传的工具类HttpPostUploadUtil.java,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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;  
    }  
   
}

我们将工具类写好之后就需要在我们消息回复中加入对应的响应代码,这里为了测试我将响应代码加在【关注事件】中!

(二)图片回复

这里我们需要修改的是我们的【事件消息业务分发器】的代码,这里我们将我们的回复加在【关注事件】中,简单代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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);
}

到这里代码基本就已经完成整个的图片消息回复的内容,同样的不论是语音回复、视频回复等流程都是一样的,所以其他的就不在做过多的讲述了,最后的大致效果如下:

正常的消息回复的内容我们就讲述的差不多了,下一篇我们讲述基于消息回复的一些应用【关键字回复及超链接回复】的实现,感谢你的翻阅,如有疑问可以留言讨论!

Java微信公众平台开发(八)--多媒体消息回复的更多相关文章

  1. Java微信公众平台开发(八)--多媒体消息回复之音乐

    我们上一篇写了关注出发图片的回复.想着在发送一次音乐,最后基于回复消息分类情况下,实现一个简单的只能话回复.先附一张大致效果图. 下面我们进入代码阶段. (一)修改消息转发器MsgDispatcher ...

  2. Java微信公众平台开发(七)--多媒体消息回复之图片回复

    之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复[普通消息类型消息],这里将讲述多媒体消息的回复方法,[多媒体消息]包含回复图片消息/回复语音消息/回复视频消息/回复音乐消 ...

  3. Java微信公众平台开发(三)--接收消息的分类及实体的创建

    转自:http://www.cuiyongzhi.com/post/41.html 前面一篇有说道应用服务器和腾讯服务器是通过消息进行通讯的,并简单介绍了微信端post的消息类型,这里我们将建立消息实 ...

  4. Java微信公众平台开发【番外篇】(七)--公众平台测试帐号的申请

    转自:http://www.cuiyongzhi.com/post/45.html 前面几篇一直都在写一些比较基础接口的使用,在这个过程中一直使用的都是我个人微博认证的一个个人账号,原本准备这篇是写[ ...

  5. Java微信公众平台开发_02_启用服务器配置

    源码将在晚上上传到 github 一.准备阶段 需要准备事项: 1.一个能在公网上访问的项目: 见:[  Java微信公众平台开发_01_本地服务器映射外网  ] 2.一个微信公众平台账号: 去注册: ...

  6. Java微信公众平台开发_07_JSSDK图片上传

    一.本节要点 1.获取jsapi_ticket //2.获取getJsapiTicket的接口地址,有效期为7200秒 private static final String GET_JSAPITIC ...

  7. 微信公众平台开发,模板消息,网页授权,微信JS-SDK,二维码生成(4)

    微信公众平台开发,模板消息,什么是模板消息,模板消息接口指的是向用户发送重要的服务通知,只能用于符合场景的要求中去,如信用卡刷卡通知,购物成功通知等等.不支持广告营销,打扰用户的消息,模板消息类有固定 ...

  8. Java微信公众平台开发--番外篇,对GlobalConstants文件的补充

    转自:http://www.cuiyongzhi.com/post/63.html 之前发过一个[微信开发]系列性的文章,也引来了不少朋友观看和点评交流,可能我在写文章时有所疏忽,对部分文件给出的不是 ...

  9. Java微信公众平台开发(十二)--微信用户信息的获取

    转自:http://www.cuiyongzhi.com/post/56.html 前面的文章有讲到微信的一系列开发文章,包括token获取.菜单创建等,在这一篇将讲述在微信公众平台开发中如何获取微信 ...

随机推荐

  1. LeetCode OJ:Combination Sum (组合之和)

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...

  2. 遮罩效果 css3

    CSS3提供了遮罩效果,这是以前CSS2中比较难实现的一个新特性,配合SVG或者canvas同样也可以实现遮罩效果,他的效果就如下图所示: 简单的说就是在一个层上面加一个过滤层,过滤层透明度越低,底层 ...

  3. java中Arrays和Collections等工具类

    java.util.Arrays类能方便地操作数组,它提供的所有方法都是静态的.具有以下功能: ² 给数组赋值:通过fill方法. ² 对数组排序:通过sort方法,按升序. ² 比较数组:通过equ ...

  4. Web目录结构

    /: Web应用的跟目录,该目录下所有文件在客户端都可以访问(JSP,HTML) /WEB-INF: 存放应用使用的各种资源.该目录及其子目录对客户端都是不可以访问的, 其中包括web.xml(部署表 ...

  5. Skynet服务器框架(八) 任务和消息调度机制

    引言: 在我看来,消息和任务调度应该是skynet的核心,整个skynet框架的核心其实就是一个消息管理系统.在skynet中可以把每个功能都当做一个服务,整个skynet工程在执行过程中会创建很多个 ...

  6. js 获取服务器当前时间

    //获取服务器时间 function getNowDate(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new window.XMLHttp ...

  7. 【剑指offer】数组中的逆序对,C++实现

    原创博文,转载请注明出处!本题牛客网地址 博客文章索引地址 博客文章中代码的github地址 1.题目 2.思路 3.代码 class Solution { public: int InversePa ...

  8. 【MFC】如何在MFC创建的程序中更改主窗口的属性 与 父窗口 WS_CLIPCHILDREN 样式 对子窗口刷新的影响 与 窗体区域绘制问题WS_CLIPCHILDREN与WS_CLIPSIBLINGS

    如何在MFC创建的程序中更改主窗口的属性 摘自:http://blog.sina.com.cn/s/blog_4bebc4830100aq1m.html 在MFC创建的单文档界面中: (基于对话框的, ...

  9. 关于15桥梁课程1&2的笔记以及待做事项的梳理

    1.指针所占用的空间是固定的 2.void *malloc(sizeof(int)); (这玩意耗时间,老师说通过内存池解决) free(p);free(p);   两次free()报错,正确的做法: ...

  10. BZOJ - 5427:最长上升子序列 (二分&思维)

    现在给你一个长度为n的整数序列,其中有一些数已经模糊不清了,现在请你任意确定这些整数的值, 使得最长上升子序列最长.(为何最长呢?因为hxy向来对自己的rp很有信心)   Input 第一行一个正整数 ...