1. 程式人生 > >Java微信公眾平臺開發(八)--多媒體訊息回覆

Java微信公眾平臺開發(八)--多媒體訊息回覆

轉自: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 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,如下:

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=