微信公众平台 图片 java_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 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 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 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 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 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 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 entity) {
UploadMediasResult result = null;
TreeMap params = new TreeMap<>();
params.put("access_token", accessToken);
// post 提交的參數
TreeMap> dataParams = new TreeMap>();
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 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 params = new TreeMap();
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 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 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 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 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;
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
總結
以上是生活随笔為你收集整理的微信公众平台 图片 java_Java微信公众平台之素材管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 古着(说一说古着的简介)
- 下一篇: java kettle log_kett