(10)java代码实现回复music类型的消息

来源:互联网 发布:阿里云先知社区 编辑:程序博客网 时间:2024/06/17 09:33

1 上传缩略图thumb,返回thumb_media_id

  • 首先需要注意:

    缩略图(thumb):64KB,支持JPG格式

    所以,需要使用软件将图片压缩到64kb的大小,我使用的是格式工厂

  • 测试类

下面代码用来获取微信服务器返回的thumb_media_id
@Test    public void testMusicThumbMediaId() throws Exception{        String path = "D:/wxSource/Wake.jpg";        String mediaId = weiXinUtil.upload(path, weiXinUtil.getAccessToken().getAccess_token(), "thumb");//{"type":"thumb","thumb_media_id":"Zq1X4RRjoPGuFCDMC9pdvWkDvkBJej5811NGhI8VnKgvtHCogfZOZsy-Q5WwP4j2","created_at":1504599769}        System.out.println("上传musicThumbImage后的thumb_media_id:"+mediaId);    }
  • upload方法
public static String upload(String filePath,String accessToken,String type) throws IOException{        File file = new File(filePath);        if (!file.isFile() || !file.exists()) {            throw new IOException("文件不存在");        }        String url = UploadUrl.replace("ACCESS_TOKEN", accessToken).replaceAll("TYPE", type);        URL urlObj = new URL(url);        HttpURLConnection connection = (HttpURLConnection)urlObj.openConnection();        connection.setRequestMethod("POST");        connection.setDoInput(true);        connection.setDoOutput(true);        connection.setUseCaches(false);        //设置请求头        connection.setRequestProperty("Connection", "Keep-Alive");        connection.setRequestProperty("Charset", "utf-8");        //设置边界        String BOUNDARY = "----------"+System.currentTimeMillis();        connection.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=\"flie\";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(connection.getOutputStream());        out.write(head);        //文件正文部分,把文件以流的方式push到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.close();        StringBuffer buffer = new StringBuffer();        BufferedReader reader = null;        String result = null;        try {            //读取url响应结果            reader=new BufferedReader(new InputStreamReader(connection.getInputStream() ));            String line = null;            while((line = reader.readLine())!=null){                buffer.append(line);            }            if (result==null) {                result=buffer.toString();            }        } catch (Exception e) {            // TODO: handle exception        } finally {            if (reader!=null) {                reader.close();            }        }        JSONObject jsonObject = JSONObject.fromObject(result);        System.out.println(jsonObject);        String typeName = "media_id";//上传image,video,voice后返回的media_id名称不同        if (!"image".equals(type)) {            typeName = type+"_media_id";        }        System.out.println("typeName="+typeName);        String mediaId = jsonObject.getString(typeName);        return mediaId;    }
  • Music对象
public class Music {    private String Title;    private String Description;    private String MusicUrl;    private String HQMusicUrl;    private String ThumbMediaId;    public String getTitle() {        return Title;    }    public void setTitle(String title) {        Title = title;    }    public String getDescription() {        return Description;    }    public void setDescription(String description) {        Description = description;    }    public String getMusicUrl() {        return MusicUrl;    }    public void setMusicUrl(String musicUrl) {        MusicUrl = musicUrl;    }    public String getHQMusicUrl() {        return HQMusicUrl;    }    public void setHQMusicUrl(String hQMusicUrl) {        HQMusicUrl = hQMusicUrl;    }    public String getThumbMediaId() {        return ThumbMediaId;    }    public void setThumbMediaId(String thumbMediaId) {        ThumbMediaId = thumbMediaId;    }
  • musicMessage 对象
public class musicMessage extends baseMessage{    private Music Music;    public Music getMusic() {        return Music;    }    public void setMusic(Music music) {        Music = music;    }}
  • musicMessageToXml方法
public static String musicMessageToXml(musicMessage musicMessage){        XStream stream = new XStream();//System.out.println(stream.toXML(text));//全类名<zk.entity.textMessage>        stream.alias("xml",musicMessage.getClass());//首尾全类名改成<xml>        return stream.toXML(musicMessage);    }
  • sendMusicMessage方法
public static String sendMusicMessage(String toUserName,String fromUserName) throws Exception{        String message = null;        String thumb_mdeia_id ="mGE_mRMLGYnZLsGHMaa-_eVuOGkpS0s4YUK_6t7IAc61ThLRVUnJaLpZ3V1cenO8";        Music music = new Music();        music.setTitle("Wake");        music.setDescription("演唱者为hillsong young and free乐队,歌曲隶属于专辑《We Are Young and Free》");        music.setMusicUrl("http://2wh8ui.natappfree.cc/WinXin/wxSource/Wake.mp3");        music.setHQMusicUrl("http://2wh8ui.natappfree.cc/WinXin/wxSource/Wake.mp3");        music.setThumbMediaId(thumb_mdeia_id);//检查thumb_media_id是否在有效期内        musicMessage musicMessage = new musicMessage();        musicMessage.setToUserName(fromUserName);        musicMessage.setFromUserName(toUserName);        musicMessage.setCreateTime(new Date().getTime());        musicMessage.setMsgType(userResp_message_type_music);        musicMessage.setMusic(music);        message = musicMessageToXml(musicMessage);        System.out.println(message);        return message;    }
  • 用户输入C就返回此音乐
if ("C".equals(map.get("Content").toUpperCase())) {                        reponseMessage = messageUtil.sendMusicMessage(toUserName, fromUserName);                    }
  • 测试
    这里写图片描述
阅读全文
0 0