Java微信公眾平臺開發(fā)(8) 多媒體消息回復(fù)
之前我們在做消息回復(fù)的時(shí)候我們對回復(fù)的消息簡單做了分類,前面也有講述如何回復(fù)【普通消息類型消息】,這里將講述多媒體消息的回復(fù)方法,【多媒體消息】包含回復(fù)圖片消息/回復(fù)語音消息/回復(fù)視頻消息/回復(fù)音樂消息,這里以圖片消息的回復(fù)為例進(jìn)行講解!
還記得之前將消息分類的標(biāo)準(zhǔn)就是一種是不需要上傳多媒體資源到騰訊服務(wù)器的而另外一種是需要的,所以在這里我們所需要做的第一步就是上傳資源到騰訊服務(wù)器,這里我們調(diào)用【素材管理】接口(后面將會有專門的章節(jié)講述)進(jìn)行圖片的上傳,同樣的這個(gè)接口可以提供我們對語音、視頻、音樂等消息的管理,這里以圖片為例(文檔地址:http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html )。在文檔中我們可以發(fā)現(xiàn)這里上傳的方式是模擬表單的方式上傳,然后返回給我們我們需要在回復(fù)消息中需要用到的參數(shù):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=
然后我在這里寫了一個(gè)模擬表單上傳的工具類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頭和上傳文件內(nèi)容的分隔符
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();
// 讀取返回?cái)?shù)據(jù)
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("發(fā)送POST請求出錯(cuò)。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
}
我們將工具類寫好之后就需要在我們消息回復(fù)中加入對應(yīng)的響應(yīng)代碼,這里為了測試我將響應(yīng)代碼加在【關(guān)注事件】中!
(二)圖片回復(fù)
這里我們需要修改的是我們的【事件消息業(yè)務(wù)分發(fā)器】的代碼,這里我們將我們的回復(fù)加在【關(guān)注事件】中,簡單代碼如下:
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)) { // 關(guān)注事件
System.out.println("==============這是關(guān)注事件!");
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);
}
到這里代碼基本就已經(jīng)完成整個(gè)的圖片消息回復(fù)的內(nèi)容,同樣的不論是語音回復(fù)、視頻回復(fù)等流程都是一樣的,所以其他的就不在做過多的講述了,最后的大致效果如下:

正常的消息回復(fù)的內(nèi)容我們就講述的差不多了,下一篇我們講述基于消息回復(fù)的一些應(yīng)用【關(guān)鍵字回復(fù)及超鏈接回復(fù)】的實(shí)現(xiàn),感謝你的翻閱,如有疑問可以留言討論!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java微信公眾平臺開發(fā)(15) 微信JSSDK的使用
- Java微信公眾平臺開發(fā)(14) 微信web開發(fā)者工具使用
- Java微信公眾平臺開發(fā)(12) 微信用戶信息的獲取
- Java微信公眾平臺開發(fā)(10) 微信自定義菜單的創(chuàng)建實(shí)現(xiàn)
- Java微信公眾平臺開發(fā)(9) 關(guān)鍵字回復(fù)以及客服接口實(shí)現(xiàn)
- Java微信公眾平臺開發(fā)(7) 公眾平臺測試帳號的申請
- Java微信公眾平臺開發(fā)(5) 文本及圖文消息回復(fù)的實(shí)現(xiàn)
- Java微信公眾平臺之素材管理
- Java微信公眾平臺之獲取地理位置
- Java微信公眾平臺之群發(fā)接口(高級群發(fā))
相關(guān)文章
Java虛擬機(jī)類加載器之雙親委派機(jī)制模型案例
這篇文章主要介紹了Java虛擬機(jī)類加載器之雙親委派機(jī)制模型案例,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
spring boot activiti工作流的搭建與簡單使用
這篇文章主要給大家介紹了關(guān)于spring boot activiti工作流的搭建與簡單使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08
springboot @ConditionalOnMissingBean注解的作用詳解
這篇文章主要介紹了springboot @ConditionalOnMissingBean注解的作用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
詳解hibernate雙向多對多關(guān)聯(lián)映射XML與注解版
本篇文章主要介紹了詳解hibernate雙向多對多關(guān)聯(lián)映射XML與注解版,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
SpringBoot中事務(wù)失效的六個(gè)原因解析
這篇文章主要介紹了SpringBoot中事務(wù)失效的六個(gè)原因解析,由于Spring的事務(wù)是基于AOP的方式結(jié)合動態(tài)代理來實(shí)現(xiàn)的,因此事務(wù)方法一定要是public的,這樣才能便于被Spring做事務(wù)的代理和增強(qiáng),需要的朋友可以參考下2023-10-10

