微信公众平台永久素材管理:(使用时间:2018-11-12 16:55)
官方文档地址:详情可参考(https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729)
1. 获取accessToken (本地测试需要在微信平台添加IP白名单)
2. 添加永久素材
素材类型说明:
素材的格式大小等要求与公众平台官网一致:
图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
视频(video):10MB,支持MP4格式
缩略图(thumb):64KB,支持JPG格式
注:我请求使用的是http请求的,https的我没试,应该是一样的结果
3. 获取永久素材(由于官网说明,将获取方法分为两种)
所以我写了两种方法(不包括图文):
获取永久素材(图片,音频,缩略图):返回文件内容,由于功能需要,将文件流转化为字节流,输出到页面上
获取视频素材:官网说明,视频素材接口返回一个JSON串
{
"title":TITLE,
"description":DESCRIPTION,
"down_url":DOWN_URL,
}
获取图文素材: 也可以获取视频素材那个接口,毕竟都是返回一个JSON,只是返回的内容不一样,可针对官网文档就行相应修改
4. 删除永久素材
代码如下:
WeChatConstant 常量类:
public class WeChatConstant {
/**
* 获取access_token的URL
*/
public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static final String WeChat_APPID="你的APPID";
public static final String WeChat_APPSECRET="你的APPSECRET";
//上传永久素材
public static final String ADD_PERMANENT_MATERIAL_URL="http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##";
//获取永久素材(下载)
public static final String GET_PERMANENT_MATERIAL_URL="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN";
//删除永久素材
public static final String DELETE_PERMANENT_MATERIAL_URL="https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=ACCESS_TOKEN";
}
WechatUtils接口工具类:
注:由于使用MVC进行文件上传使用到MultipartFile,可自行将转化
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.cdd.common.entity.AccessToken;
import com.cdd.common.lang.Strings;
/**
*
* @Description: 微信接口公共类
* @author WEICY
* @date 2018年11月12日
* @version v1.0.0
*/
public class WeChatUtils {
/**
* Get请求,方便到一个url接口来获取结果
* @param url
* @return
*/
public static JSONObject doGetStr(String url){
HttpClient client = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try{
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 获取access_token
* @return
*/
public static AccessToken getAccessToken(){
AccessToken accessToken = new AccessToken();
String url = WeChatConstant.ACCESS_TOKEN_URL.replace("APPID" ,WeChatConstant.WeChat_APPID).replace("APPSECRET",WeChatConstant.WeChat_APPSECRET);
JSONObject jsonObject = doGetStr(url);
if(jsonObject !=null){
System.out.println(jsonObject.toString());
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpireIn(jsonObject.getInt("expires_in"));
}
return accessToken;
}
/**
*
* @Description: 永久上传多媒体文件
* 上传视频最好小于10M
* @author WEICY
* @date 2018年11月8日
* @version v1.0.0
* @param accessToken
* @param file 上传的文件
* @param mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
* @param title 上传类型为video的参数
* @param introduction 上传类型为video的参数
* @return
*/
public static JSONObject uploadPermanentMedia(String accessToken,
MultipartFile file,String mediaType,String title,String introduction) {
JSONObject jsonObject=null;
try {
//如果video传输的两个参数为空的话,就取文件名称
if(Strings.isEmpty(title)||Strings.isEmpty(introduction)){
title=file.getName();
introduction=title;
}
//这块是用来处理如果上传的类型是video的类型的
JSONObject j=new JSONObject();
j.put("title", title);
j.put("introduction", introduction);
// 拼装请求地址
String uploadMediaUrl = WeChatConstant.ADD_PERMANENT_MATERIAL_URL;
uploadMediaUrl = uploadMediaUrl.replace("##ACCESS_TOKEN##",
accessToken);
URL url = new URL(uploadMediaUrl);
String result = null;
long filelength = file.getSize();
String fileName=file.getOriginalFilename();
//文件后缀名
String suffix=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
String type=mediaType+"/"+suffix;
// String type="video/mp4";
//根据文件后缀suffix将type的值设置成对应的mime类型的值
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界,这里的boundary是http协议里面的分割符,不懂的可惜百度(http 协议 boundary),这里boundary 可以是任意的值(111,2222)都行
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
//这块是post提交type的值也就是文件对应的mime类型值
sb.append("--"); // 必须多两道线 这里说明下,这两个横杠是http协议要求的,用来分隔提交的参数用的,不懂的可以看看http 协议头
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"type\" \r\n\r\n"); //这里是参数名,参数名和值之间要用两次
sb.append(type+"\r\n"); //参数的值
/**
* 这块是上传video是必须的参数(title,introduction)
* 重点说明下,这两个参数完全可以卸载url地址后面 就想我们平时url地址传参一样,
* http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##&type=""&description={} 这样,如果写成这样,上面的
* 那两个参数的代码就不用写了,不过media参数能否这样提交我没有试,感兴趣的可以试试
*/
if(mediaType.equals("video")){
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"description\" \r\n\r\n");
sb.append(j.toString()+"\r\n");
}
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
//这里是media参数相关的信息,这里是否能分开下我没有试,感兴趣的可以试试
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""
+ fileName + "\";filelength=\"" + filelength + "\" \r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
System.out.println(sb.toString());
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(file.getInputStream());
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分,这里结尾表示整体的参数的结尾,结尾要用"--"作为结束,这些都是http协议的规定
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
// 定义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();
}
// 使用JSON-lib解析返回结果
jsonObject = JSONObject.fromObject(result);
if (jsonObject.has("media_id")) {
System.out.println("media_id:"+jsonObject.getString("media_id"));
} else {
System.out.println(jsonObject.toString());
}
System.out.println("json:"+jsonObject.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return jsonObject;
}
/**
*
* @Description: 获取微信永久素材(不包括视频,图文素材)
* @author WEICY
* @date 2018年11月12日
* @version v1.0.0
* @param accessToken
* @param mediaId
* @Desc 素材说明:
其他类型的素材消息,则响应的直接为素材的内容,开发者可以自行保存为文件
错误:{"errcode":40007,"errmsg":"invalid media_id"}
* @return
* @throws Exception
*/
public static byte[] getPermanentMedia(String accessToken,String mediaId) throws Exception {
byte[] buffer = null;
//0.准备好json请求参数
Map paramMap=new HashMap();
paramMap.put("media_id", mediaId);
Object data=JSON.toJSON(paramMap);
//1.生成一个请求
String url=WeChatConstant.GET_PERMANENT_MATERIAL_URL.replace("ACCESS_TOKEN", accessToken);
HttpPost httpPost = new HttpPost(url);
//2.配置请求属性
//2.1 设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
httpPost.setConfig(requestConfig);
//2.2 设置数据传输格式-json
httpPost.addHeader("Content-Type", "application/json");
//2.3 设置请求参数
StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
httpPost.setEntity(requestEntity);
//3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//4. 发起请求,获取响应信息
response = httpClient.execute(httpPost, new BasicHttpContext());
//请求成功
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
//5.取得请求内容
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream input = entity.getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = input.read(b)) != -1) {
bos.write(b, 0, n);
}
input.close();
bos.close();
buffer = bos.toByteArray();
}
if (entity != null) {
entity.consumeContent();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
//释放资源
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer;
}
/**
*
* @Description: 获取微信永久素材(视频,图文)
* @author WEICY
* @date 2018年11月12日
* @version v1.0.0
* @param accessToken
* @param mediaId
* @Desc 素材说明:
视频消息素材:
{
"title":TITLE,
"description":DESCRIPTION,
"down_url":DOWN_URL,
}
图文素材:
{
"articles": [{
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"author": AUTHOR,
"digest": DIGEST,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"content": CONTENT,
"content_source_url": CONTENT_SOURCE_URL,
"need_open_comment":1,
"only_fans_can_comment":1
},
//若新增的是多图文素材,则此处应还有几段articles结构
]
}
错误:{"errcode":40007,"errmsg":"invalid media_id"}
其他类型的素材消息,则响应的直接为素材的内容,开发者可以自行保存为文件
* @return
* @throws Exception
*/
public static JSONObject getVideoPermanentMedia(String accessToken, String mediaId) throws Exception {
JSONObject jsonObject=null;
//0.准备好json请求参数
Map paramMap=new HashMap();
paramMap.put("media_id", mediaId);
Object data=JSON.toJSON(paramMap);
//1.生成一个请求
String url=WeChatConstant.GET_PERMANENT_MATERIAL_URL.replace("ACCESS_TOKEN", accessToken);
HttpPost httpPost = new HttpPost(url);
//2.配置请求属性
//2.1 设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
httpPost.setConfig(requestConfig);
//2.2 设置数据传输格式-json
httpPost.addHeader("Content-Type", "application/json");
//2.3 设置请求参数
StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
httpPost.setEntity(requestEntity);
//3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//4. 发起请求,获取响应信息
response = httpClient.execute(httpPost, new BasicHttpContext());
//请求成功
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
//5.取得请求内容
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
if (entity != null) {
entity.consumeContent();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
//释放资源
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return jsonObject;
}
/**
*
* @Description: 删除永久素材
* @author WEICY
* @date 2018年11月12日
* @version v1.0.0
* @param mediaId
* @param accessToken
* @return
* @throws Exception
*/
public static int deletePermanentMaterial(String mediaId,String accessToken) throws Exception {
int num=0;
//0.准备好json请求参数
Map paramMap=new HashMap();
paramMap.put("media_id", mediaId);
Object data=JSON.toJSON(paramMap);
//1.生成一个请求
String url=WeChatConstant.DELETE_PERMANENT_MATERIAL_URL.replace("ACCESS_TOKEN", accessToken);
HttpPost httpPost = new HttpPost(url);
//2.配置请求属性
//2.1 设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
httpPost.setConfig(requestConfig);
//2.2 设置数据传输格式-json
httpPost.addHeader("Content-Type", "application/json");
//2.3 设置请求实体,封装了请求参数
StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
httpPost.setEntity(requestEntity);
//3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//3.3 发起请求,获取响应
response = httpClient.execute(httpPost, new BasicHttpContext());
//获取响应内容
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = JSONObject.fromObject(result);
if(jsonObject.has("errcode")&&jsonObject.getString("errcode").equals("0")){
num=1;
}
}
} catch (IOException e) {
System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close(); //释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
return num;
}
}