评论

java微信测试公众号实现文本、图片消息回复

微信测试公众号实现文本、图片消息回复

学习记录:

源码地址:http://github.crmeb.net/u/LXT

1.申请微信测试公众号:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421137522

2.配置测试公众号

URL:能够让微信服务器请求到的网址也就是提供一个外网给微信服务器,后面这个wx_check就是微信服务器请求你的校验Token的请求(如不知道或没有外网端口的可以参考我上面的的文章"使用ngrok实现外网穿透(一)"地址:https://blog.csdn.net/csdn_ljl/article/details/94234532
,我用的是ngrok实现的外网映射
Token:随便写什么,只要与后台一致就行

Controller:
/**
     * 校验
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wx_check",method = {RequestMethod.GET})
    public void wxCheck(HttpServletRequest request, HttpServletResponse response) throws  Exception{
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        System.out.print(echostr);
        PrintWriter out = response.getWriter();
        if (WeiXinCheck.weiXinCheckSignature(signature,timestamp,nonce)){
            out.print(echostr);
        }
    }
    WeiXinCheck:
		private static final  String token = "admin";
    /**
     * 签名校验
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean weiXinCheckSignature(String signature,String timestamp,String nonce){
        String[] arr = new String[]{token,timestamp,nonce};
        //排序
        Arrays.sort(arr);

        //生成字符串
        StringBuffer content = new StringBuffer();
        for (int i =0; i<arr.length;i++){
            content.append(arr[i]);
        }

        //sha1加密
        String temp = getSha1(content.toString());
        return temp.equals(signature);
    }
    /**
     * sha1加密
     * @param str
     * @return
     */
    public static String getSha1(String str) {
        if (null == str || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

3.微信请求格式、及后台响应代码

1.文本消息回复

微信请求格式:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453

文本消息格式:
<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[this is a test]]></Content>
  <MsgId>1234567890123456</MsgId>
</xml>

参数				描述
ToUserName		开发者微信号
FromUserName	发送方帐号(一个OpenID)
CreateTime		消息创建时间 (整型)
MsgType			消息类型,文本为text
Content			文本消息内容
MsgId			消息id,64位整型

Controller:
/**
     * 文本消息回复
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wx_check",method = {RequestMethod.POST})
    public void wxCheck2(HttpServletRequest request, HttpServletResponse response)throws Exception{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        try {
            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;
            if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {

             

                /**
                 * 文本消息回复
                 */
                TextMessage text = new TextMessage();
                text.setFromUserName(toUserName);
                text.setToUserName(fromUserName);
                text.setCreateTime(new Date().getTime()+"");
                text.setMsgType("text");
                text.setContent("您发送的消息是:"+ content);
                message = MessageUtil.textMessageToxml(text);
            }
            System.out.print(message);
            printWriter.print(message);
        }catch (DocumentException e){
            e.printStackTrace();
        }finally {
            printWriter.close();
        }
    }
MessageUtil:
/**
     * xml转换为map集合
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();

        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);
        Element root = doc.getRootElement();

        List<Element> list = root.elements();
        for (Element element : list) {
            map.put(element.getName(), element.getText());
        }
        ins.close();
        return map;
    }

文本消息实体类:
package com.jl.controller.po;

public class TextMessage {
    private String ToUserName;
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String Content;
    private String MsgId;

    public String getToUserName() {
        return ToUserName;
    }

    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }

    public String getFromUserName() {
        return FromUserName;
    }

    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }

    public String getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(String createTime) {
        CreateTime = createTime;
    }

    public String getMsgType() {
        return MsgType;
    }

    public void setMsgType(String msgType) {
        MsgType = msgType;
    }

    public String getContent() {
        return Content;
    }

    public void setContent(String content) {
        Content = content;
    }

    public String getMsgId() {
        return MsgId;
    }

    public void setMsgId(String msgId) {
        MsgId = msgId;
    }
}

MessageUtil:
/**
     * 将文本对象转换为xml
     *
     * @param textMessage
     * @return
     */
    public static String textMessageToxml(TextMessage textMessage) {
        XStream xStream = new XStream();
        xStream.alias("xml", textMessage.getClass());
        return xStream.toXML(textMessage);
    }

结果如图:

2.图片消息回复

微信图片回复格式:
图片消息

```<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[image]]></MsgType>
  <PicUrl><![CDATA[this is a url]]></PicUrl>
  <MediaId><![CDATA[media_id]]></MediaId>
  <MsgId>1234567890123456</MsgId>
</xml>

参数					描述
ToUserName		开发者微信号
FromUserName	发送方帐号(一个OpenID)
CreateTime		消息创建时间 (整型)
MsgType			消息类型,图片为image
PicUrl			图片链接(由系统生成)
MediaId			图片消息媒体id,可以调用获取临时素材接口拉取数据。
MsgId			消息id,64位整型
```j
校验签名必须要的哦别忘了
Controller:
/**
     * 图片消息回复
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wx_check",method = {RequestMethod.POST})
    public void wxCheck2(HttpServletRequest request, HttpServletResponse response)throws Exception{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        try {
            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;
            if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {

                /**
                 * 图片消息回复
                 */
                message= MessageUtil.initNewsMessage(toUserName,fromUserName);

               
            }
            System.out.print(message);
            printWriter.print(message);
        }catch (DocumentException e){
            e.printStackTrace();
        }finally {
            printWriter.close();
        }
    }
MessageUtil:
	public static final String MESSAGE_TEXT = "text";//文本消息
    public static final String MESSAGE_IMAGE = "image";//图片消息
    public static final String MESSAGE_VOICE = "voice";//语音消息
    public static final String MESSAGE_VIDEO = "video";//视频
    public static final String MESSAGE_SHORTVIDEO = "shortvideo";//小视屏
    public static final String MESSAGE_LOCATION = "location";//地理位置
    public static final String MESSAGE_LINK = "link";//链接
    public static final String MESSAGE_EVENT = "event";//事件推送
    public static final String MESSAGE_SUBSCRIBE = "subscribe";//被关注
    public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";//取消关注
    public static final String MESSAGE_CLICK = "CLICK";//点击
    public static final String MESSAGE_VIEW = "VIEW";//

    /**
     * 图片消息组装
     * @param toUserName
     * @param fromUserName
     * @return
     */
        public static String initNewsMessage (String toUserName, String fromUserName)throws  Exception{
            String message = null;
            Image image = new Image();

            AccessToken token = WeiXinUtil.getAccessToken();
            System.out.print("票据:"+token.getToken());
            System.out.print("有效时间:"+token.getExpiresIn());
            image.setMediaId(WeiXinUtil.upload("img/0.jpg",token.getToken(),"image"));

            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;
        }

Image:
package com.jl.controller.po;

public class Image {
    private String MediaId;

    public String getMediaId() {
        return MediaId;
    }

    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }
}
ImageMessage:
package com.jl.controller.po;

public class ImageMessage extends BaseMessage {
    private Image Image;

    public com.jl.controller.po.Image getImage() {
        return Image;
    }

    public void setImage(com.jl.controller.po.Image image) {
        Image = image;
    }
}
AccessToken:
package com.jl.controller.po;

public class AccessToken {
	private String token;
	private int expiresIn;
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	public int getExpiresIn() {
		return expiresIn;
	}
	public void setExpiresIn(int expiresIn) {
		this.expiresIn = expiresIn;
	}
}
BaseMessage:
package com.jl.controller.po;

public class BaseMessage {

    private String ToUserName;
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String MediaId;

    public String getToUserName() {
        return ToUserName;
    }

    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }

    public String getFromUserName() {
        return FromUserName;
    }

    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }

    public String getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(String createTime) {
        CreateTime = createTime;
    }

    public String getMsgType() {
        return MsgType;
    }

    public void setMsgType(String msgType) {
        MsgType = msgType;
    }

    public String getMediaId() {
        return MediaId;
    }

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


    
 WeiXinUtil:
				private static final String APPID = "写自己的";
			    private static final String APPSECRET = "写自己的";
			
			    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
			
			    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
			
			    private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
			
			    private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
			
			    private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

/**
     * get请求
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject doGetStr(String url) throws ParseException, IOException{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        HttpResponse httpResponse = client.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        return jsonObject;
    }
    /**
     * POST请求
     * @param url
     * @param outStr
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpost = new HttpPost(url);
        JSONObject jsonObject = null;
        httpost.setEntity(new StringEntity(outStr,"UTF-8"));
        HttpResponse response = client.execute(httpost);
        String result = EntityUtils.toString(response.getEntity(),"UTF-8");
        jsonObject = JSONObject.fromObject(result);
        return jsonObject;
    }

        (下载图片获得mediaid)
        /**
     * 文件下载
     * @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);
        System.out.println(jsonObj);
        String typeName = "media_id";
        if(!"image".equals(type)){
            typeName = type + "_media_id";
        }
        String mediaId = jsonObj.getString(typeName);
        return mediaId;
    }
 
    /**
     * 获取accessToken
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static AccessToken getAccessToken() throws ParseException, IOException{
        AccessToken token = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        JSONObject jsonObject = doGetStr(url);
        if(jsonObject!=null){
            token.setToken(jsonObject.getString("access_token"));
            token.setExpiresIn(jsonObject.getInt("expires_in"));
        }
        return token;
    }
    MessageUtil:
/**
     * 将图片对象转换为xml
     *
     * @param imageMessage
     * @return
     */
    public static String imageMessageToxml(ImageMessage imageMessage) {
        XStream xStream = new XStream();
        xStream.alias("xml", imageMessage.getClass());
        return xStream.toXML(imageMessage);
    }

结果如图:

如不成功请上码云下载源码核对,地址:http://github.crmeb.net/u/LXT

最后一次编辑于  08-24  
点赞 1
收藏
评论