文章目录
一、新增临时素材
接口调用请求说明
http请求方式:POST/FORM,
使用https
https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE
参数说明
参数 是否必须 说明
access_token 是 调用接口凭证
type 是 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
media 是 form-data中媒体文件标识,有filename、filelength、content-type等信息
返回说明
正确情况下的返回JSON数据包结果如下:
{“type”:“TYPE”,“media_id”:“MEDIA_ID”,“created_at”:123456789}
参数 描述
type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb,主要用于视频与音乐格式的缩略图)
media_id 媒体文件上传后,获取标识
created_at 媒体文件上传时间戳
错误情况下的返回JSON数据包示例如下(示例为无效媒体类型错误):
{“errcode”:40004,“errmsg”:“invalid media type”}
上传临时素材代码
上传临时素材的方法
/**
* 上传临时文件方法
* @param filePath
* @param type
* @return
* @throws Exception
*/
public String uploadPic(String filePath,String type) throws Exception{
//获得你的access_token
String redisToken = wxService.getRedisToken();
//地址https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
String urlStr = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
String replaceUrl = urlStr.replace("ACCESS_TOKEN", redisToken).replace("TYPE", type);
//返回结果
String result=null;
File file=new File(filePath);
if(!file.exists()||!file.isFile()){
throw new IOException("文件不存在");
}
URL url=new URL(replaceUrl);
HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");//以POST方式提交表单
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);//POST方式不能使用缓存
//设置请求头信息
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
//设置边界
String BOUNDARY="----------"+System.currentTimeMillis();
conn.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=\"media\"; filename=\"" + file.getName()+"\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
System.out.println("sb:"+sb);
//获得输出流
OutputStream out=new DataOutputStream(conn.getOutputStream());
//输出表头
out.write(sb.toString().getBytes("UTF-8"));
//文件正文部分
//把文件以流的方式 推送道URL中
DataInputStream din=new DataInputStream(new FileInputStream(file));
int bytes=0;
byte[] buffer=new byte[1024];
while((bytes=din.read(buffer))!=-1){
out.write(buffer,0,bytes);
}
din.close();
//结尾部分
byte[] foot=("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
out.write(foot);
out.flush();
out.close();
if(HttpsURLConnection.HTTP_OK==conn.getResponseCode()){
StringBuffer strbuffer=null;
BufferedReader reader=null;
try {
strbuffer=new StringBuffer();
reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineString=null;
while((lineString=reader.readLine())!=null){
strbuffer.append(lineString);
}
if(result==null){
result=strbuffer.toString();
System.out.println("result:"+result);
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!"+e);
e.printStackTrace();
}finally{
if(reader!=null){
reader.close();
}
}
}
return result;
}
查看上传的临时素材
接口调用请求说明
http请求方式: GET
https调用 https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
直接浏览器get请求访问即可下载
下载上传的临时素材代码
方法代码
/**
* 获得临时素材 下载文件 只要得到输入流,就可以从流中读出数据
*/
//TODO 字符乱码问题: 因为响应是图片格式 所以并不是字符编码问题
@Test
public void test8() throws Exception {
String redisToken = wxService.getRedisToken();
String urlStr = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
String replaceUrl = urlStr.replace("ACCESS_TOKEN", redisToken).replace("MEDIA_ID", "FtA17e_zIAqlFyfOZ-tpkbhPmZFQ-EIKGef4NwwPfNaPqGARTs4eX7yrX8gAV5Mv");
System.out.println(replaceUrl);
try {
URL url = new URL(replaceUrl);
//得到connection对象。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//连接
connection.connect();
//得到响应码
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("responseMessage:"+responseMessage);
/**
* 获取所有的响应头信息
*/
// Map<String, List<String>> headerFields = connection.getHeaderFields();
// Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
// System.out.println("headerFields:"+headerFields);
//
// for (Map.Entry<String, List<String>> entry : entries) {
// System.out.println("Key : " + entry.getKey() +" ,Value : " + entry.getValue());
// }
//获取响应头信息 Content-disposition
String headerField = connection.getHeaderField("Content-disposition");
System.out.println("headerField:"+headerField);
//从响应头总中提取文件名
String filename = headerField.substring(headerField.indexOf("\"")+1,headerField.lastIndexOf("\""));
if(responseCode == HttpURLConnection.HTTP_OK){
//得到响应流
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
//将响应流转换成字符串
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file,true);
byte[] bytes = new byte[1024];
int len;
while((len =inputStream.read(bytes))!= -1){
fos.write(bytes,0,len);
}
fos.flush();
// 释放资源
inputStream.close();
fos.close();
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
二、新增永久图文素材
1、最近更新:永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。
2、公众号的素材库保存总数量有上限:图文消息素材、图片素材上限为100000,其他类型为1000。
3、素材的格式大小等要求与公众平台官网一致:
图片(image): 10M,支持bmp/png/jpeg/jpg/gif格式
语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
视频(video):10MB,支持MP4格式
缩略图(thumb):64KB,支持JPG格式
4、图文消息的具体内容中,微信后台将过滤外部的图片链接,图片url需通过"上传图文消息内的图片获取URL"接口上传图片获取。
5、"上传图文消息内的图片获取URL"接口所上传的图片,不占用公众号的素材库中图片数量的100000个的限制,图片仅支持jpg/png格式,大小必须在1MB以下。
6、图文消息支持正文中插入自己帐号和其他公众号已群发文章链接的能力。
1.上传图文消息内的图片获取URL
接口调用请求说明:
http请求方式: POST,https协议 https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
返回说明 正常情况下的返回结果为:
{
“url”: “http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0”
}
代码:
/**
* 上传图文消息内的图片获取URL
* http请求方式: POST,https协议 以表单形式提交
* https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
*/
@Test
public void test6(){
String redisToken = wxService.getRedisToken();
String urlStr = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
String replaceUrl = urlStr.replace("ACCESS_TOKEN", redisToken);
File file = new File("/Users/LiuShihao/IdeaProjects/wxthepublic/FtA17e_zIAqlFyfOZ-tpkbhPmZFQ-EIKGef4NwwPfNaPqGARTs4eX7yrX8gAV5Mv.jpg");
StringBuilder resp = new StringBuilder();
String result=null;
try {
URL urlObj = new URL(replaceUrl);
HttpsURLConnection conn = (HttpsURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");//以POST方式提交表单
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Charset","UTF-8");
//数据边界
String boundary = "----------"+System.currentTimeMillis();
conn.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
//获取输出流
OutputStream out = conn.getOutputStream();
//创建文件输入流
FileInputStream fis = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(boundary);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\"; filename=\""+file.getName()+"\"\r\n");
sb.append("Content-Type: applicatin/octet-stream\r\n\r\n");
out.write(sb.toString().getBytes());
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) != -1){
out.write(bytes,0,len);
}
String foot = "\r\n--"+boundary+"--\r\n";
out.write(foot.getBytes());
out.flush();
out.close();
//读取数据
if(HttpsURLConnection.HTTP_OK==conn.getResponseCode()){
StringBuffer strbuffer=null;
BufferedReader reader=null;
try {
strbuffer=new StringBuffer();
reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineString=null;
while((lineString=reader.readLine())!=null){
strbuffer.append(lineString);
}
result=strbuffer.toString();
} catch (IOException e) {
System.out.println("发送POST请求出现异常!"+e);
e.printStackTrace();
}finally{
if(reader!=null){
reader.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
//resp:{"url":"http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\/OsaJQib8ibD8ActRfkHSkvZsntjEjmicVGibcWic0Kbkq8pgnf4BJgytEOUBxmlIM1IBCPsWLOXUW0dUwAZziaiajwNfw\/0"}
//http://mmbiz.qpic.cn/mmbiz_jpg/OsaJQib8ibD8ActRfkHSkvZsntjEjmicVGibcWic0Kbkq8pgnf4BJgytEOUBxmlIM1IBCPsWLOXUW0dUwAZziaiajwNfw/0
}
其中url就是上传图片的URL,可放置图文消息中使用。
2.新增其他类型永久素材(image、voice、video、thumb)
通过POST表单来调用接口,表单id为media,包含需要上传的素材内容,有filename、filelength、content-type等信息。
http请求方式: POST https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE
上传其他永久素材代码:
/**
* 新增其他类型永久素材 https POST
* 通过POST表单来调用接口,表单id为media,包含需要上传的素材内容,有filename、filelength、content-type等信息
* https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE
*/
@Test
public void test9(){
String redisToken = wxService.getRedisToken();
String str ="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
String replace1 = str.replace("ACCESS_TOKEN", redisToken).replace("TYPE", "image");
// String replace = str.replace("ACCESS_TOKEN", redisToken).replace("TYPE", "voice");
File file = new File("/Users/LiuShihao/IdeaProjects/wxthepublic/FtA17e_zIAqlFyfOZ-tpkbhPmZFQ-EIKGef4NwwPfNaPqGARTs4eX7yrX8gAV5Mv.jpg");
StringBuilder resp = new StringBuilder();
String result=null;
try {
URL urlObj = new URL(replace1);
HttpsURLConnection conn = (HttpsURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");//以POST方式提交表单
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Charset","UTF-8");
//数据边界
String boundary = "----------"+System.currentTimeMillis();
conn.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
//获取输出流
OutputStream out = conn.getOutputStream();
//创建文件输入流
FileInputStream fis = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(boundary);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\"; filename=\""+file.getName()+"\"\r\n");
sb.append("Content-Type: applicatin/octet-stream\r\n\r\n");
out.write(sb.toString().getBytes());
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) != -1){
out.write(bytes,0,len);
}
String foot = "\r\n--"+boundary+"--\r\n";
out.write(foot.getBytes());
out.flush();
out.close();
//读取数据
if(HttpsURLConnection.HTTP_OK==conn.getResponseCode()){
StringBuffer strbuffer=null;
BufferedReader reader=null;
try {
strbuffer=new StringBuffer();
reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineString=null;
while((lineString=reader.readLine())!=null){
strbuffer.append(lineString);
}
result=strbuffer.toString();
} catch (IOException e) {
System.out.println("发送POST请求出现异常!"+e);
e.printStackTrace();
}finally{
if(reader!=null){
reader.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
//{"media_id":"q27RhD1fN9vtgwdtzGIURdEVO6-Xi1UCqxN3rQMjqXA",
// "url":"http://mmbiz.qpic.cn/mmbiz_jpg/OsaJQib8ibD8ActRfkHSkvZsntjEjmicVGibcWic0Kbkq8pgnf4BJgytEOUBxmlIM1IBCPsWLOXUW0dUwAZziaiajwNfw/0?wx_fmt=jpeg",
// "item":[]}
}
3.新增永久图文素材
http请求方式: POST,https协议 https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN
略
4.获取永久素材
https协议POST请求https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN
5.删除永久素材
http请求方式: POSThttps://api.weixin.qq.com/cgi-bin/material/del_material?access_token=ACCESS_TOKEN
6.获取素材总数
http请求方式: GET https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN
7.获取素材列表
http请求方式: POST https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN