之前我們在做消息回復的時候我們對回復的消息簡單做了分類,前面也有講述如何回復【普通消息類型消息】,這里將講述多媒體消息的回復方法,【多媒體消息】包含回復圖片消息/回復語音消息/回復視頻消息/回復音樂消息,這里以圖片消息的回復為例進行講解!
還記得之前將消息分類的標准就是一種是不需要上傳多媒體資源到騰訊服務器的而另外一種是需要的,所以在這里我們所需要做的第一步就是上傳資源到騰訊服務器,這里我們調用【素材管理】接口(后面將會有專門的章節講述)進行圖片的上傳,同樣的這個接口可以提供我們對語音、視頻、音樂等消息的管理,這里以圖片為例(文檔地址:http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html )。在文檔中我們可以發現這里上傳的方式是模擬表單的方式上傳,然后返回給我們我們需要在回復消息中需要用到的參數:media_id!
(一)素材接口圖片上傳
按照之前我們的約定將接口請求的url寫入到配置文件interface_url.properties中:
1 #獲取token的url 2 tokenUrl=https://api.weixin.qq.com/cgi-bin/token 3 #永久多媒體文件上傳url 4 mediaUrl=http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=
然后我在這里寫了一個模擬表單上傳的工具類HttpPostUploadUtil.java,代碼如下:
1 package com.gede.wechat.util; 2 3 import java.io.BufferedReader; 4 import java.io.DataInputStream; 5 import java.io.DataOutputStream; 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.InputStreamReader; 9 import java.io.OutputStream; 10 import java.net.HttpURLConnection; 11 import java.net.URL; 12 import java.util.Iterator; 13 import java.util.Map; 14 15 import javax.activation.MimetypesFileTypeMap; 16 17 import com.gede.web.util.GlobalConstants; 18 19 /** 20 * @author gede 21 * @version date:2019年5月26日 下午8:47:28 22 * @description : 23 */ 24 public class HttpPostUploadUtil { 25 26 public String urlStr; 27 28 public HttpPostUploadUtil() { 29 urlStr = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" 30 + GlobalConstants.getInterfaceUrl("access_token") + "&type=image"; 31 } 32 33 /** 34 * 上傳圖片 35 * 36 * @param urlStr 37 * @param textMap 38 * @param fileMap 39 * @return 40 */ 41 @SuppressWarnings("rawtypes") 42 public String formUpload(Map<String, String> textMap, Map<String, String> fileMap) { 43 String res = ""; 44 HttpURLConnection conn = null; 45 String BOUNDARY = "---------------------------123821742118716"; // boundary就是request頭和上傳文件內容的分隔符 46 try { 47 URL url = new URL(urlStr); 48 conn = (HttpURLConnection) url.openConnection(); 49 conn.setConnectTimeout(5000); 50 conn.setReadTimeout(30000); 51 conn.setDoOutput(true); 52 conn.setDoInput(true); 53 conn.setUseCaches(false); 54 conn.setRequestMethod("POST"); 55 conn.setRequestProperty("Connection", "Keep-Alive"); 56 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); 57 conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); 58 59 OutputStream out = new DataOutputStream(conn.getOutputStream()); 60 // text 61 if (textMap != null) { 62 StringBuffer strBuf = new StringBuffer(); 63 Iterator<?> iter = textMap.entrySet().iterator(); 64 while (iter.hasNext()) { 65 Map.Entry entry = (Map.Entry) iter.next(); 66 String inputName = (String) entry.getKey(); 67 String inputValue = (String) entry.getValue(); 68 if (inputValue == null) { 69 continue; 70 } 71 strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); 72 strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); 73 strBuf.append(inputValue); 74 } 75 out.write(strBuf.toString().getBytes()); 76 } 77 78 // file 79 if (fileMap != null) { 80 Iterator<?> iter = fileMap.entrySet().iterator(); 81 while (iter.hasNext()) { 82 Map.Entry entry = (Map.Entry) iter.next(); 83 String inputName = (String) entry.getKey(); 84 String inputValue = (String) entry.getValue(); 85 if (inputValue == null) { 86 continue; 87 } 88 File file = new File(inputValue); 89 String filename = file.getName(); 90 String contentType = new MimetypesFileTypeMap().getContentType(file); 91 if (filename.endsWith(".jpg")) { 92 contentType = "image/jpg"; 93 } 94 if (contentType == null || contentType.equals("")) { 95 contentType = "application/octet-stream"; 96 } 97 98 StringBuffer strBuf = new StringBuffer(); 99 strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); 100 strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename 101 + "\"\r\n"); 102 strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); 103 104 out.write(strBuf.toString().getBytes()); 105 106 DataInputStream in = new DataInputStream(new FileInputStream(file)); 107 int bytes = 0; 108 byte[] bufferOut = new byte[1024]; 109 while ((bytes = in.read(bufferOut)) != -1) { 110 out.write(bufferOut, 0, bytes); 111 } 112 in.close(); 113 } 114 } 115 116 byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 117 out.write(endData); 118 out.flush(); 119 out.close(); 120 121 // 讀取返回數據 122 StringBuffer strBuf = new StringBuffer(); 123 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 124 String line = null; 125 while ((line = reader.readLine()) != null) { 126 strBuf.append(line).append("\n"); 127 } 128 res = strBuf.toString(); 129 reader.close(); 130 reader = null; 131 } catch (Exception e) { 132 System.out.println("發送POST請求出錯。" + urlStr); 133 e.printStackTrace(); 134 } finally { 135 if (conn != null) { 136 conn.disconnect(); 137 conn = null; 138 } 139 } 140 return res; 141 } 142 143 }
我們將工具類寫好之后就需要在我們消息回復中加入對應的響應代碼,這里為了測試我將響應代碼加在【關注事件】中!
(二)圖片回復
這里我們需要修改的是我們的【事件消息業務分發器】的代碼,這里我們將我們的回復加在【關注事件】中,簡單代碼如下:
1 String openid = map.get("FromUserName"); // 用戶openid 2 String mpid = map.get("ToUserName"); // 公眾號原始ID 3 ImageMessage imgmsg = new ImageMessage(); 4 imgmsg.setToUserName(openid); 5 imgmsg.setFromUserName(mpid); 6 imgmsg.setCreateTime(new Date().getTime()); 7 imgmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_Image); 8 if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // 關注事件 9 System.out.println("==============這是關注事件!"); 10 Image img = new Image(); 11 HttpPostUploadUtil util=new HttpPostUploadUtil(); 12 String filepath="H:\\1.jpg"; 13 Map<String, String> textMap = new HashMap<String, String>(); 14 textMap.put("name", "testname"); 15 Map<String, String> fileMap = new HashMap<String, String>(); 16 fileMap.put("userfile", filepath); 17 String mediaidrs = util.formUpload(textMap, fileMap); 18 System.out.println(mediaidrs); 19 String mediaid=JSONObject.fromObject(mediaidrs).getString("media_id"); 20 img.setMediaId(mediaid); 21 imgmsg.setImage(img); 22 return MessageUtil.imageMessageToXml(imgmsg); 23 }
到這里代碼基本就已經完成整個的圖片消息回復的內容,同樣的不論是語音回復、視頻回復等流程都是一樣的,下一篇再練習一個關於語音回復的,最后的大致效果如下: