圖片、語音消息回覆
一、圖片、語音消息回覆xml結構
1.1 回覆圖片消息XML
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<Voice>
<MediaId><![CDATA[media_id]]></MediaId>
</Voice>
</xml>
1.2 圖片消息的bean
/**
*
* 類名稱: Image
* 類描述: 圖片
* @author yuanjun
* 創建時間:2017年12月8日下午6:42:39
*/
public class Image {
private String MediaId;//素材id
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
}
import com.yuanjun.weixindemo.bean.BaseMessage;
import com.yuanjun.weixindemo.bean.Image;
/**
*
* 類名稱: ImageMessage
* 類描述: 圖片消息
* @author yuanjun
* 創建時間:2017年12月8日下午6:44:10
*/
public class ImageMessage extends BaseMessage{
private Image Image;//Image節點
public Image getImage() {
return Image;
}
public void setImage(Image image) {
Image = image;
}
}
註明:如何根據回覆信息的xml結構,構建實體類,看xml的節點特徵,名字需要對應,並且注意大小寫1.3回覆語音消息XML結構結構
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[media_id]]></MediaId>
</Image>
</xml>
1.4 語音消息bean
/**
*
* 類名稱: Voice
* 類描述:
* @author yuanjun
* 創建時間:2017年12月8日下午6:49:41
*/
public class Voice {
private String MediaId;
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
}
/**
*
* 類名稱: VoiceMessage
* 類描述: 語音消息
* @author yuanjun
* 創建時間:2017年12月8日下午6:48:36
*/
public class VoiceMessage extends BaseMessage{
private Voice Voice;
public Voice getVoice() {
return Voice;
}
public void setVoice(Voice voice) {
Voice = voice;
}
}
二、 獲取MediaId
通過素材管理中的接口上傳多媒體文件,得到的id。圖片,語音,視頻都是類似的結構。可在開發文檔的素材管理新增臨時素材找到如何獲取
MediaId,通過調用接口獲取MediaId。具體可參考https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726的文檔說明。由於個人
訂閱號沒有接口權限,此時需要採用測試賬號進行接口開發。在開發管理選擇公衆平臺的測試賬號,並開通。
2.1 獲取的步驟參考文檔https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726
注意:在獲取access_token時,需將appid和祕鑰換成測試賬號的,可參考http://blog.csdn.net/shenbug/article/details/78752888
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import net.sf.json.JSONObject;
/**
*
* 類名稱: UploadUtil
* 類描述: 文件上傳工具類
* @author yuanjun
* 創建時間:2017年12月8日下午6:57:18
*/
public class UploadUtil {
private static final String UPLOAD_URL ="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
/**
* 文件上傳
* @param filePath
* @param accessToken
* @param type
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
URL urlObj = new URL(url);
//連接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//設置請求頭信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
//設置邊界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
//獲得輸出流
OutputStream out = new DataOutputStream(con.getOutputStream());
//輸出表頭
out.write(head);
//文件正文部分
//把文件已流文件的方式 推入到url中
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[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定義最後數據分隔線
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String result = null;
try {
//定義BufferedReader輸入流來讀取URL的響應
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
JSONObject jsonObj = JSONObject.fromObject(result);
String typeName = "media_id";
if("thumb".equals(type)){
typeName = type + "_media_id";
}
String mediaId = jsonObj.getString(typeName);
return mediaId;
}
}
2.2 測試
三、封裝信息回覆xml
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import com.thoughtworks.xstream.XStream;
import com.yuanjun.weixindemo.bean.Image;
import com.yuanjun.weixindemo.bean.ImageMessage;
import com.yuanjun.weixindemo.util.BaseMessageUtil;
import com.yuanjun.weixindemo.util.UploadUtil;
import com.yuanjun.weixindemo.util.WeiXinUtil;
public class ImageMessageUtil implements BaseMessageUtil<ImageMessage> {
/**
* 將信息轉爲xml格式
*/
public String messageToxml(ImageMessage imageMessage) {
XStream xtream = new XStream();
xtream.alias("xml", imageMessage.getClass());
xtream.alias("Image", new Image().getClass());
return xtream.toString();
}
/**
* 封裝信息
*/
public String initMessage(String FromUserName, String ToUserName) {
Image image = new Image();
image.setMediaId(getmediaId());
ImageMessage message = new ImageMessage();
message.setFromUserName(ToUserName);
message.setToUserName(FromUserName);
message.setCreateTime(new Date().getTime());
message.setImage(image);
return messageToxml(message);
}
/**
* 獲取Media
* @return
*/
public String getmediaId(){
String path = "f:/1.jpg";
String accessToken = WeiXinUtil.getAccess_Token();
String mediaId = null;
try {
mediaId = UploadUtil.upload(path, accessToken, "image");
} catch (KeyManagementException | NoSuchAlgorithmException
| NoSuchProviderException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaId;
}
}
四、控制器post請求,回覆信息,實現回覆圖片,顯示圖片
@RequestMapping(value = "wxdemo",method=RequestMethod.POST)
public void dopost(HttpServletRequest request,HttpServletResponse response){
response.setCharacterEncoding("utf-8");
PrintWriter out = null;
//將微信請求xml轉爲map格式,獲取所需的參數
Map<String,String> map = MessageUtil.xmlToMap(request);
String ToUserName = map.get("ToUserName");
String FromUserName = map.get("FromUserName");
String MsgType = map.get("MsgType");
String Content = map.get("Content");
String message = null;
//處理文本類型,實現輸入1,回覆相應的封裝的內容
if("text".equals(MsgType)){
if("圖片".equals(Content)){
ImageMessageUtil util = new ImageMessageUtil();
message = util.initMessage(FromUserName, ToUserName);
}else{
TextMessageUtil textMessage = new TextMessageUtil();
message = textMessage.initMessage(FromUserName, ToUserName,Content);
}
}
try {
out = response.getWriter();
out.write(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
}
五、效果(只展示圖片的效果,語言可參照圖片的方法完成)
注意:需要在關測試的公衆號,才能顯示功能,否則在原來的公衆號會出現該公衆號提供的服務出現故障,請稍後再試。