目录

前言

上一篇中获取到mediId后就可以开始实现回复图片消息了。

看看文档

微信公众号开发 - 7.回复图片消息

大概就是这个样子的

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
    <Image>
    <MediaId><![CDATA[media_id]]></MediaId>
    </Image>
</xml>

创建实体

Image对象

package cn.notemi.po;

/**
 * Title:Image
 * Description:
 *
 * @author Flicker
 * @create 2017-07-26 下午 6:51
 **/
public class Image {
    private String MediaId;

    public String getMediaId() {
        return MediaId;
    }

    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }
}

ImageMessage对象

继承我们之前的BaseMessage

package cn.notemi.po;

/**
 * Title:ImageMessage
 * Description:
 *
 * @author Flicker
 * @create 2017-07-26 下午 6:52
 **/
public class ImageMessage extends BaseMessage{
    private Image Image;

    public Image getImage() {
        return Image;
    }

    public void setImage(Image image) {
        Image = image;
    }
}

转化拼接图片消息

package cn.notemi.util;

import cn.notemi.po.*;
import com.thoughtworks.xstream.XStream;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;

/**
 * Title:MessageUtil
 * Description:消息的转换
 *
 * @author Flicker
 * @create 2017-07-25 下午 8:19
 **/
public class MessageUtil {

    public static final String MESSAGE_IMAGE = "image";

    /**
     * 将图片消息消息对象转为xml
     * @param imageMessage
     * @return
     */
    public static String ImageMessageToXml(ImageMessage imageMessage){
        XStream xStream = new XStream();
        xStream.alias("xml",imageMessage.getClass());
        return xStream.toXML(imageMessage);
    }

    /**
     * 图片消息的拼接
     * @param toUserName
     * @param fromUserName
     * @return
     */
    public static String initImageMessage(String toUserName,String fromUserName){
        String message = null;
        Image image = new Image();
        //这里填写mediaId
        image.setMediaId("oJ5D3Rt2qPsUH42U9v4tNFi8N3GDL4ixWDzFjywlKtdrOIiVvMA_U965lUEJ0AYu");
        ImageMessage imageMessage = new ImageMessage();
        imageMessage.setFromUserName(toUserName);
        imageMessage.setToUserName(fromUserName);
        imageMessage.setMsgType(MESSAGE_IMAGE);
        imageMessage.setCreateTime(new Date().getTime());
        imageMessage.setImage(image);

        message = ImageMessageToXml(imageMessage);
        return message;
    }
}

controller

            if("3".equals(content)){
                message = MessageUtil.initImageMessage(toUserName,fromUserName);
            }

测试

微信公众号开发 - 7.回复图片消息

源代码

Weixin.rar