SpringBoot开发微信公众号(四)

图片、语音消息回复

一、图片、语音消息回复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();
	}

五、效果(只展示图片的效果,语言可参照图片的方法完成)

注意:需要在关测试的公众号,才能显示功能,否则在原来的公众号会出现该公众号提供的服务出现故障,请稍后再试。


效果展示




猜你喜欢

转载自blog.csdn.net/shenbug/article/details/78754540