WeChat material management and mass posting are not Java-friendly. This article only introduces the new temporary materials and the new permanent materials, and adds the rest by obtaining, deleting, and modifying them.
There are often scenarios where temporary multimedia materials are needed for official accounts. For example, when using interfaces, especially when sending messages, operations such as obtaining and calling multimedia files, multimedia messages, are performed through media_id. The material management interface is open to all certified subscription numbers and service numbers .
Material limitations
Image: 2M, supports PNG/JPEG/JPG/GIF format voice: 2M, playback length does not exceed 60s, supports AMR/MP3 format video (video): 10MB, supports MP4 format thumbnails: 64KB, supports JPG format
1. Add temporary materials
Interface: https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE, and then pass a media file type, which can be image (image), voice (voice), video (video) and thumbnail (thumb).
1. Subscription and service accounts must be certified
2. Temporary material media_id is reusable
3. The media file is stored in the WeChat background for 3 days, that is, media_id will be invalid after 3 days.
/** * Upload temporary material (local) * * @param accessToken * @param type * Media file types, including image (image), voice (voice), video (video) and thumbnails (thumb) * @param path * Image 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; } /** * Upload temporary material (network) * * @param accessToken * @param type * Media file types, including image (image), voice (voice), video (video) and thumbnails (thumb) * @param path * Image 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; }2. Add permanent materials
Interface: https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE, media file types, including image (image), voice (voice), video (video, exception) and thumbnail (thumb)
/** * Upload permanent material (local) * * @param accessToken * @param type * Media file types, including image (image), voice (voice), video (video) and thumbnails (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; } /** * Upload permanent material (network) * * @param accessToken * @param type * Media file types, including image (image), voice (voice), video (video) and thumbnails (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; }Special attention should be paid to adding permanent video materials. When uploading video materials, you need to POST another form, with the id description, including the description information of the material title and introduction, and the content format is JSON.
/** * Upload permanent material (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; } /** * Upload permanent material (video, network) * * @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; }3. Add permanent graphic materials
Interface: https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN, please refer to the UploadNewsMedia entity class for post information.
For commonly used materials, developers can upload them to the WeChat server through this interface and use them permanently.
1. After the permanent image material is added, it will be returned to the developer with a URL. The developer can use it within the Tencent domain name (use it outside the Tencent domain name, and the picture will be blocked).
2. The total number of saved materials in the official account is limited to: the upper limit of graphic and text message materials and picture materials is 5,000, and other types are 1,000.
3. In the specific content of the graphic and text messages, the WeChat backend will filter external image links, and the image url needs to be uploaded through the "Upload the image in the graphic and text messages to obtain URL" interface.
4. The pictures uploaded on the "Upload pictures in the text messages to get URLs" interface do not occupy the limit of 5,000 pictures in the material library of the official account. The pictures only support jpg/png format, and the size must be less than 1MB.
5. The graphic and text messages support the ability to insert your own account and other public accounts into the main text and have posted links to the article.
/** * Material for uploading permanent graphic and text messages* * @param accessToken * Authorized token * @param entity * Image and text message object* @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 Submitted parameters 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; }4. Upload the pictures in the text message to get the URL
Interface: https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
The pictures uploaded on this interface do not occupy the limit of 5,000 pictures in the material library of the official account. Images only support jpg/png format, and the size must be less than 1MB. The url returned by this interface is the URL to upload the image, which can be placed in text messages.
/** * Upload the image in the text message to get the URL (local) * * @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; } /** * Upload the image in the text message to get the URL (network) * * @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; }V. Some tools
Configuration class
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";
Upload graphic and text message material return class
package com.phil.wechat.msg.model.media; /** * Results returned by uploading graphic and text message materials* @author phil * @date September 20, 2017* */ public class UploadMediasResult { private String type; // Media file types, including image (image), voice (voice), video (video) and thumbnail (thumb), the number of times is news, that is, private String media_id; // Media file/unique identifier obtained after uploading graphic and text messages private String created_at; // Media file upload time}Upload graphic and text message material entity class
package com.phil.wechat.msg.model.media; import java.io.Serializable; /** * Upload graphic message material entity class* @author phil * @date September 20, 2017*/ public class UploadNewsMedia implements Serializable { private static final long serialVersionUID = 6551817058101753854L; private String thumb_media_id; // media_id of the thumbnail of the graphic message can obtain private String author in the basic support-upload multimedia file interface; // author of the graphic message private String title; // Title of the graphic message private String content_source_url; // Click the link to read the original text private String content; // Content of the graphic message page supports HTML tag private String digest; // Description of the graphic message private int show_conver_pic; // Whether it is displayed as cover 1 means it is displayed as cover 0 does not display as cover }Upload method
/** * Upload media file (local) * * @param method * Request method GET/POST * @param path * Api path * @param param * Api parameter * @param mediaPath * The path of image/music to be uploaded * @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); // Set request header information con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", SystemConfig.DEFAULT_CHARACTER_ENCODING); // Set boundary String boundary = "-----------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Request text information// Part 1 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); // File body part// Push the file into the url by streaming the file inputStream = new DataInputStream(new FileInputStream(file)); IOUtils.copy(inputStream, output); // Ending part 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; } /** * Upload media file (cannot be local) * * @param method * Request method GET/POST * @param path * Api path * @param param * api parameter * @param mediaPath * The path of image/music to be uploaded * @param connTime * The connection time is default to 5000 * @param readTime * The read time is default to 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(); // Get file extension 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(); // Get input stream 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; } /** * Upload Video media file (local) * * @param method * Request method GET/POST * @param path * Api path * @param param * Api parameter* @param mediaPath * The path of the voide to be uploaded * @param title * Video title * @param introduction * Video description * @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); // Set request header information con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", SystemConfig.DEFAULT_CHARACTER_ENCODING); // Set boundary String boundary = "-----------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Request body information// Part 1 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); // File body part// Push the file into the url by streaming the file inputStream = new DataInputStream(new FileInputStream(file)); IOUtils.copy(inputStream, output); // Ending part 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; } /** * Upload Video media file (network) * * @param method * Request method GET/POST * @param path * Api path * @param param * Api parameter * @param mediaPath * The path of the voide to be uploaded * @param title * Video title * @param introduction * Video description * @param connTime * The connection time defaults to 5000 * @param readTime * The default reading time is 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); // Ending part 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(); // Get input stream 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; }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.