Java微信公众平台之素材管理
微信素材管理和群发这块对java很不友好。本文只对新增临时素材,新增永久素材做介绍,其余获取、删除、修改自行补充
公众号经常有需要用到一些临时性的多媒体素材的场景,例如在使用接口特别是发送消息时,对多媒体文件、多媒体消息的获取和调用等操作,是通过media_id来进行的。素材管理接口对所有认证的订阅号和服务号开放。
素材的限制
图片(image): 2m,支持png\jpeg\jpg\gif格式
语音(voice):2m,播放长度不超过60s,支持amr\mp3格式
视频(video):10mb,支持mp4格式
缩略图(thumb):64kb,支持jpg格式
一、新增临时素材
接口:https://api.weixin.qq.com/cgi-bin/media/upload?access_token=access_token&type=type,再传一个媒体文件类型,可以是图片(image)、语音(voice)、视频(video)和缩略图(thumb)。
1、订阅号和服务号要通过认证
2、临时素材media_id是可复用的
3、媒体文件在微信后台保存时间为3天,即3天后media_id失效。
/** * 上传临时素材(本地) * * @param accesstoken * @param type * 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @param path * 图片路径 * @return */ public static uploadmediasresult uploadtempmediafile(string accesstoken, string type, string path) { uploadmediasresult result = null; treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); params.put("type", type); try { string json = httpsuploadmediafile(systemconfig.post_method, wechatconfig.upload_temp_media_type_url, params, path); result = jsonutil.fromjsonstring(json, uploadmediasresult.class); } catch (exception e) { e.printstacktrace(); } return result; } /** * 上传临时素材(网络) * * @param accesstoken * @param type * 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @param path * 图片路径 * @return */ public static uploadmediasresult uploadtempmedia(string accesstoken, string type, string path) { uploadmediasresult result = null; treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); params.put("type", type); try { string json = httpsuploadmedia(systemconfig.post_method, wechatconfig.upload_temp_media_type_url, params, path, 0, 0); result = jsonutil.fromjsonstring(json, uploadmediasresult.class); } catch (exception e) { e.printstacktrace(); } return result; }
二、新增永久素材
接口:https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=access_token&type=type,媒体文件类型,分别有图片(image)、语音(voice)、视频(video,例外)和缩略图(thumb)
/** * 上传永久素材(本地) * * @param accesstoken * @param type * 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @return */ public static uploadmediasresult uploadforevermediafile(string accesstoken, string type, string path) { uploadmediasresult result = null; treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); params.put("type", type); try { string json = httpsuploadmediafile(systemconfig.post_method, wechatconfig.upload_forever_media_type_url, params, path); result = jsonutil.fromjsonstring(json, uploadmediasresult.class); } catch (exception e) { e.printstacktrace(); } return result; } /** * 上传永久素材(网络) * * @param accesstoken * @param type * 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @return */ public static uploadmediasresult uploadforevermedia(string accesstoken, string type, string path) { uploadmediasresult result = null; treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); params.put("type", type); try { string json = httpsuploadmedia(systemconfig.post_method, wechatconfig.upload_forever_media_type_url, params, path, 0, 0); result = jsonutil.fromjsonstring(json, uploadmediasresult.class); } catch (exception e) { e.printstacktrace(); } return result; }
新增永久视频素材需特别注意,在上传视频素材时需要post另一个表单,id为description,包含素材的描述信息title和introduction,内容格式为json
/** * 上传永久素材(video) * * @param accesstoken * @return */ public static string uploadforevermediafile(string accesstoken, string title, string introduction, string path) { treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); params.put("type", "video"); string mediaid = null; try { string json = httpsuploadvideomediafile(systemconfig.post_method, wechatconfig.upload_forever_media_type_url, params, path, title, introduction); mediaid = jsonutil.fromjsonstring(json, "media_id"); } catch (exception e) { e.printstacktrace(); } return mediaid; } /** * 上传永久素材(video,网络) * * @param accesstoken * @return */ public static string uploadforevermedia(string accesstoken, string title, string introduction, string path) { treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); params.put("type", "video"); string mediaid = null; try { string json = httpsuploadvideomedia(systemconfig.post_method, wechatconfig.upload_forever_media_type_url, params, path, title, introduction, 0, 0); mediaid = jsonutil.fromjsonstring(json, "media_id"); } catch (exception e) { e.printstacktrace(); } return mediaid; }
三、新增永久图文素材
接口:https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=access_token,post信息参见uploadnewsmedia 实体类
对于常用的素材,开发者可通过本接口上传到微信服务器,永久使用.
1、永久图片素材新增后,将带有url返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。
2、公众号的素材库保存总数量有上限:图文消息素材、图片素材上限为5000,其他类型为1000。
3、图文消息的具体内容中,微信后台将过滤外部的图片链接,图片url需通过"上传图文消息内的图片获取url"接口上传图片获取。
4、"上传图文消息内的图片获取url"接口所上传的图片,不占用公众号的素材库中图片数量的5000个的限制,图片仅支持jpg/png格式,大小必须在1mb以下。
5、图文消息支持正文中插入自己帐号和其他公众号已群发文章链接的能力。
/** * 上传永久图文消息的素材 * * @param accesstoken * 授权token * @param entity * 图文消息对象 * @return */ public static uploadmediasresult uploadnewsmedia(string accesstoken, list<uploadnewsmedia> entity) { uploadmediasresult result = null; treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); // post 提交的参数 treemap<string, list<uploadnewsmedia>> dataparams = new treemap<string, list<uploadnewsmedia>>(); dataparams.put("articles", entity); string data = jsonutil.tojsonstring(dataparams); string json = httprequtil.httpsdefaultexecute(systemconfig.post_method, wechatconfig.upload_forever_news_media_url, params, data); result = jsonutil.fromjsonstring(json, uploadmediasresult.class); return result; }
四、上传图文消息内的图片获取url
接口:https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=access_token
本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1mb以下,此接口返回的url就是上传图片的url,可放置图文消息中使用。
/** * 上传图文消息内的图片获取url(本地) * * @param accesstoken * @param path * @return */ public static string uploadimgmediafile(string accesstoken, string path) { treemap<string, string> params = new treemap<>(); params.put("access_token", accesstoken); string url = null; try { string json = httpsuploadmediafile(systemconfig.post_method, wechatconfig.upload_img_media_url, params, path); url = jsonutil.fromjsonstring(json, "url"); } catch (exception e) { e.printstacktrace(); } return url; } /** * 上传图文消息内的图片获取url(网络) * * @param accesstoken * @param path * @return */ public static string uploadimgmedia(string accesstoken, string path) { treemap<string, string> params = new treemap<string, string>(); params.put("access_token", accesstoken); string url = null; try { string json = httpsuploadmedia(systemconfig.post_method, wechatconfig.upload_img_media_url, params, path, 0, 0); url = jsonutil.fromjsonstring(json, "url"); } catch (exception e) { e.printstacktrace(); } return url; }
五、部分工具类
配置类
public static final string upload_img_media_url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg"; public static final string upload_forever_news_media_url = "https://api.weixin.qq.com/cgi-bin/material/add_news"; public static final string upload_temp_media_type_url = "https://api.weixin.qq.com/cgi-bin/media/upload"; public static final string upload_forever_media_type_url = "https://api.weixin.qq.com/cgi-bin/material/add_material";
上传图文消息素材返回类
package com.phil.wechat.msg.model.media; /** * 上传图文消息素材返回的结果 * @author phil * @date 2017年9月20日 * */ public class uploadmediasresult { private string type; // 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb),次数为news,即图文消息 private string media_id; // 媒体文件/图文消息上传后获取的唯一标识 private string created_at; // 媒体文件上传时间 }
上传图文消息素材实体类
package com.phil.wechat.msg.model.media; import java.io.serializable; /** * 上传图文消息素材实体类 * @author phil * @date 2017年9月20日 */ public class uploadnewsmedia implements serializable { private static final long serialversionuid = 6551817058101753854l; private string thumb_media_id; // 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得 private string author; // 图文消息的作者 private string title; // 图文消息的标题 private string content_source_url; // 图文消息点击阅读原文的链接 private string content; // 图文消息页面的内容,支持html标签 private string digest; // 图文消息的描述 private int show_conver_pic; // 是否显示为封面 1表示显示为封面 0 不显示为封面 }
上传方法
/** * 上传媒体文件(本地) * * @param method * 请求方法 get/post * @param path * api的路径 * @param param * api参数 * @param mediapath * 待上传的image/music 的path * @return * @throws exception */ public static string httpsuploadmediafile(string method, string path, map<string, string> param, string mediapath) throws exception { string result = null; url url = new url(setparmas(param, path, "")); outputstream output = null; datainputstream inputstream = null; try { file file = new file(mediapath); if (!file.isfile() || !file.exists()) { throw new ioexception("file is not exist"); } httpurlconnection con = (httpurlconnection) url.openconnection(); con.setdoinput(true); con.setdooutput(true); con.setusecaches(false); con.setrequestmethod(systemconfig.post_method); // 设置请求头信息 con.setrequestproperty("connection", "keep-alive"); con.setrequestproperty("charset", systemconfig.default_character_encoding); // 设置边界 string boundary = "----------" + system.currenttimemillis(); con.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary); // 请求正文信息 // 第一部分 output = new dataoutputstream(con.getoutputstream()); ioutils.write(("--" + boundary + "\r\n").getbytes(systemconfig.default_character_encoding), output); ioutils.write(("content-disposition: form-data;name=\"media\"; filename=\"" + file.getname() + "\"\r\n") .getbytes(systemconfig.default_character_encoding), output); ioutils.write( "content-type:application/octet-stream\r\n\r\n".getbytes(systemconfig.default_character_encoding), output); // ioutils.write(("content-type: "+ fileext + "\r\n\r\n").getbytes(), output); // 文件正文部分 // 把文件已流文件的方式 推入到url中 inputstream = new datainputstream(new fileinputstream(file)); ioutils.copy(inputstream, output); // 结尾部分 ioutils.write(("\r\n--" + boundary + "--\r\n").getbytes(systemconfig.default_character_encoding), output); output.flush(); result = inputstreamtostring(con.getinputstream()); } catch (malformedurlexception e) { e.printstacktrace(); } catch (protocolexception e) { e.printstacktrace(); } catch (ioexception e) { throw new ioexception("read data error"); } finally { ioutils.closequietly(output); ioutils.closequietly(inputstream); } return result; } /** * 上传媒体文件(不能本地) * * @param method * 请求方法 get/post * @param path * api的路径 * @param param * api参数 * @param mediapath * 待上传的image/music 的path * @param conntime * 连接时间 默认为5000 * @param readtime * 读取时间 默认为5000 * @return * @throws exception */ public static string httpsuploadmedia(string method, string path, map<string, string> param, string mediapath, int conntime, int readtime) throws exception { string result = ""; url url = new url(setparmas(param, path, "")); outputstream output = null; bufferedinputstream inputstream = null; try { string boundary = "----"; httpurlconnection conn = getconnection(method, url); conn.setconnecttimeout(conntime == 0 ? default_conntime : conntime); conn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime); conn.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary); output = conn.getoutputstream(); url mediaurl = new url(mediapath); if (mediaurl != null) { httpurlconnection mediaconn = (httpurlconnection) mediaurl.openconnection(); mediaconn.setdooutput(true); mediaconn.setusecaches(false); mediaconn.setrequestmethod(systemconfig.get_method); mediaconn.setconnecttimeout(conntime == 0 ? default_conntime : conntime); mediaconn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime); string conntype = mediaconn.getcontenttype(); // 获得文件扩展 string fileext = getfileext(conntype); ioutils.write(("--" + boundary + "\r\n").getbytes(), output); ioutils.write(("content-disposition: form-data; name=\"media\"; filename=\"" + getfilename(mediapath) + "\"\r\n").getbytes(), output); ioutils.write(("content-type: " + fileext + "\r\n\r\n").getbytes(), output); inputstream = new bufferedinputstream(mediaconn.getinputstream()); ioutils.copy(inputstream, output); ioutils.write(("\r\n----" + boundary + "--\r\n").getbytes(), output); mediaconn.disconnect(); // 获取输入流 result = inputstreamtostring(conn.getinputstream()); } } catch (malformedurlexception e) { e.printstacktrace(); } catch (protocolexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally { ioutils.closequietly(output); ioutils.closequietly(inputstream); } return result; } /** * 上传video媒体文件(本地) * * @param method * 请求方法 get/post * @param path * api的路径 * @param param * api参数 * @param mediapath * 待上传的voide 的path * @param title * 视频标题 * @param introduction * 视频描述 * @return * @throws exception */ public static string httpsuploadvideomediafile(string method, string path, map<string, string> param, string mediapath, string title, string introduction) throws exception { string result = null; url url = new url(setparmas(param, path, "")); outputstream output = null; datainputstream inputstream = null; try { file file = new file(mediapath); if (!file.isfile() || !file.exists()) { throw new ioexception("file is not exist"); } httpurlconnection con = (httpurlconnection) url.openconnection(); con.setdoinput(true); con.setdooutput(true); con.setusecaches(false); con.setrequestmethod(systemconfig.post_method); // 设置请求头信息 con.setrequestproperty("connection", "keep-alive"); con.setrequestproperty("charset", systemconfig.default_character_encoding); // 设置边界 string boundary = "----------" + system.currenttimemillis(); con.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary); // 请求正文信息 // 第一部分 output = new dataoutputstream(con.getoutputstream()); ioutils.write(("--" + boundary + "\r\n").getbytes(systemconfig.default_character_encoding), output); ioutils.write(("content-disposition: form-data;name=\"media\"; filename=\"" + file.getname() + "\"\r\n") .getbytes(), output); ioutils.write("content-type: video/mp4 \r\n\r\n".getbytes(), output); // 文件正文部分 // 把文件已流文件的方式 推入到url中 inputstream = new datainputstream(new fileinputstream(file)); ioutils.copy(inputstream, output); // 结尾部分 ioutils.write(("--" + boundary + "\r\n").getbytes(systemconfig.default_character_encoding), output); ioutils.write("content-disposition: form-data; name=\"description\";\r\n\r\n" .getbytes(systemconfig.default_character_encoding), output); ioutils.write(("{\"title\":\"" + title + "\",\"introduction\":\"" + introduction + "\"}") .getbytes(systemconfig.default_character_encoding), output); ioutils.write(("\r\n--" + boundary + "--\r\n\r\n").getbytes(systemconfig.default_character_encoding), output); output.flush(); result = inputstreamtostring(con.getinputstream()); } catch (malformedurlexception e) { e.printstacktrace(); } catch (protocolexception e) { e.printstacktrace(); } catch (ioexception e) { throw new ioexception("read data error"); } finally { ioutils.closequietly(output); ioutils.closequietly(inputstream); } return result; } /** * 上传video媒体文件(网络) * * @param method * 请求方法 get/post * @param path * api的路径 * @param param * api参数 * @param mediapath * 待上传的voide 的path * @param title * 视频标题 * @param introduction * 视频描述 * @param conntime * 连接时间 默认为5000 * @param readtime * 读取时间 默认为5000 * @return * @throws exception */ public static string httpsuploadvideomedia(string method, string path, map<string, string> param, string mediapath, string title, string introduction, int conntime, int readtime) throws exception { string result = null; url url = new url(setparmas(param, path, "")); outputstream output = null; bufferedinputstream inputstream = null; try { string boundary = "----"; httpurlconnection conn = getconnection(method, url); conn.setconnecttimeout(conntime == 0 ? default_conntime : conntime); conn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime); conn.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary); output = conn.getoutputstream(); url mediaurl = new url(mediapath); if (mediaurl != null) { httpurlconnection mediaconn = (httpurlconnection) mediaurl.openconnection(); mediaconn.setdooutput(true); mediaconn.setusecaches(false); mediaconn.setrequestmethod(systemconfig.get_method); mediaconn.setconnecttimeout(conntime == 0 ? default_conntime : conntime); mediaconn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime); ioutils.write(("--" + boundary + "\r\n").getbytes(), output); ioutils.write(("content-disposition: form-data; name=\"media\"; filename=\"" + getfilename(mediapath) + "\"\r\n").getbytes(), output); ioutils.write("content-type: video/mp4 \r\n\r\n".getbytes(), output); inputstream = new bufferedinputstream(mediaconn.getinputstream()); ioutils.copy(inputstream, output); // 结尾部分 ioutils.write(("--" + boundary + "\r\n").getbytes(systemconfig.default_character_encoding), output); ioutils.write("content-disposition: form-data; name=\"description\";\r\n\r\n" .getbytes(systemconfig.default_character_encoding), output); ioutils.write(("{\"title\":\"" + title + "\",\"introduction\":\"" + introduction + "\"}") .getbytes(systemconfig.default_character_encoding), output); ioutils.write(("\r\n--" + boundary + "--\r\n\r\n").getbytes(systemconfig.default_character_encoding), output); mediaconn.disconnect(); // 获取输入流 result = inputstreamtostring(conn.getinputstream()); } } catch (malformedurlexception e) { e.printstacktrace(); } catch (protocolexception e) { e.printstacktrace(); } catch (ioexception e) { throw new ioexception("read data error"); } finally { ioutils.closequietly(output); ioutils.closequietly(inputstream); } return result; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。