WeChat 자료 관리 및 대량 게시는 Java 친화적이지 않습니다. 이 기사는 새로운 임시 재료와 새로운 영구 재료 만 소개하고 나머지는 획득, 삭제 및 수정하여 추가합니다.
공식 계정에는 임시 멀티미디어 자료가 필요한 시나리오가 종종 있습니다. 예를 들어, 인터페이스를 사용할 때, 특히 메시지를 보낼 때, 멀티미디어 파일 획득 및 호출과 같은 작업은 Media_id를 통해 수행됩니다. 자료 관리 인터페이스는 모든 인증 된 구독 번호 및 서비스 번호에 열려 있습니다 .
재료 제한
이미지 : 2M, PNG/JPEG/JPG/GIF 형식 음성 : 2M, 재생 길이는 60 대를 초과하지 않고 AMR/MP3 형식 비디오 (비디오) : 10MB, MP4 형식 썸네일 : 64KB, JPG Format 지원을 지원합니다.
1. 임시 재료를 추가하십시오
인터페이스 : https://api.weixin.qq.com/cgi-bin/media/upload?access_token=access_token&type=type를 전달합니다.
1. 가입 및 서비스 계정은 인증을 받아야합니다
2. 임시 자료 Media_ID는 재사용 가능합니다
3. 미디어 파일은 3 일 동안 WeChat 배경에 저장됩니다. 즉, 3 일 후에 Media_id가 유효하지 않습니다.
/ ** * 임시 자료 (로컬) * * @Param AccessToken * @Param 유형 * 이미지 (이미지), 음성 (음성), 비디오 (비디오) 및 썸네일 (@Param Path * im treemap <string, String> params = new Treemap <> (); params.put ( "access_token", accesstoken); params.put ( "type", type); {String json = httpsuploadmediafile (SystemConfig.post_method, wechatconfig.upload_temp_media_type_url, params, path); 결과 = jsonutil.fromjsonstring (json, uploadmediasresult.class); } catch (예외 e) {e.printstacktrace (); } 반환 결과; } / ** * 임시 자료 업로드 (네트워크) * * @param accesstoken * @param 유형 * 이미지 (이미지), 음성 (음성), 비디오 (비디오) 및 썸네일 * @Param Path * @return * / public uploadMediasresultTempMediA (String AccessToken, String Path)를 포함한 미디어 파일 유형을 포함합니다. 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); 결과 = jsonutil.fromjsonstring (json, uploadmediasresult.class); } catch (예외 e) {e.printstacktrace (); } 반환 결과; }2. 영구 재료를 추가하십시오
인터페이스 : https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=access_token&type=type, 이미지 (이미지), 음성 (음성), 비디오 (비디오, 예외) 및 썸네일 (Thumbnail) (Thumbnail)을 포함한 미디어 파일 유형
/ ** * 영구 자료 (로컬) * * @Param AccessToken * @param 유형 * 이미지 (이미지), 음성 (음성), 비디오 (비디오) 및 썸네일 (Thumbnails) */ public static uploadmediasresult upload foreverVerMediaFile (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); 결과 = jsonutil.fromjsonstring (json, uploadmediasresult.class); } catch (예외 e) {e.printstacktrace (); } 반환 결과; } / ** * 영구 자료 (네트워크) * * @param accesstoken * @param 유형 * 이미지 (이미지), 음성 (음성), 비디오 (비디오) 및 썸네일 (whilmnails) * / public static uploadmediasresult uploadforeververmedia (String AccessToken, 문자열, 문자열 경로)를 포함한 미디어 파일 유형을 포함합니다. 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); 결과 = jsonutil.fromjsonstring (json, uploadmediasresult.class); } catch (예외 e) {e.printstacktrace (); } 반환 결과; }영구 비디오 자료를 추가하는 데 특별한주의를 기울여야합니다. 비디오 자료를 업로드 할 때는 자료 제목 및 소개의 설명 정보를 포함하여 ID 설명과 함께 다른 양식을 게시해야하며 컨텐츠 형식은 JSON입니다.
/ ** * 영구 자료를 업로드 (비디오) * @Param AccessToken * @return */ public static string upload foreverMediaFile (String accessToken, String Titles, String 소개, 문자열 경로) {treemap <String, String> Params = new Treemap <> (); params.put ( "access_token", accesstoken); params.put ( "유형", "비디오"); 문자열 mediaid = null; try {string json = httpsuploadvideomediafile (systemconfig.post_method, wechatconfig.upload_forever_media_type_url, params, path, title, soliction); mediaid = jsonutil.fromjsonstring (json, "media_id"); } catch (예외 e) {e.printstacktrace (); } return mediaid; } / ** * 영구 자료를 업로드 (비디오, 네트워크) * @param accesstoken * @return * / public static string upload foreverMedia (String accessToken, 문자열 제목, 문자열 소개, 문자열 경로) {treemap <String, String> params = new Treemap <> (); params.put ( "access_token", accesstoken); params.put ( "유형", "비디오"); 문자열 mediaid = null; try {String JSON = httpsuploadvideomedia (SystemConfig.post_method, wechatconfig.upload_forever_media_type_url, params, path, title, 소개, 0, 0); mediaid = jsonutil.fromjsonstring (json, "media_id"); } catch (예외 e) {e.printstacktrace (); } return mediaid; }3. 영구 그래픽 자료를 추가하십시오
인터페이스 : https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=access_token, 게시물 정보는 UploadNewsMedia Entity 클래스를 참조하십시오.
일반적으로 사용되는 자료의 경우 개발자는이 인터페이스를 통해 WeChat 서버에 업로드하여 영구적으로 사용할 수 있습니다.
1. 영구 이미지 자료가 추가되면 URL이있는 개발자에게 반환됩니다. 개발자는 Tencent 도메인 이름 내에서 사용할 수 있습니다 (Tencent 도메인 이름 외부에서 사용하면 그림이 차단됩니다).
2. 공식 계정의 저장된 재료의 총 수는 다음으로 제한됩니다. 그래픽 및 문자 메시지 자료 및 그림 자료의 상한은 5,000이고 다른 유형은 1,000입니다.
3. 그래픽 및 문자 메시지의 특정 콘텐츠에서 WeChat 백엔드는 외부 이미지 링크를 필터링하며 이미지 URL을 "그래픽 및 문자 메시지에 업로드하여 URL"인터페이스를 얻으려면 업로드해야합니다.
4. "URL을 얻기 위해 문자 메시지의 사진 업로드"에 업로드 된 그림은 공식 계정의 자료 라이브러리에서 5,000 장의 사진 한계를 차지하지 않습니다. 그림은 JPG/PNG 형식 만 지원하며 크기는 1MB 미만이어야합니다.
5. 그래픽 및 문자 메시지는 자신의 계정 및 기타 공개 계정을 본문에 삽입하고 기사에 대한 링크를 게시하는 기능을 지원합니다.
/ ** * 영구 그래픽 및 문자 메시지를 업로드하기위한 자료 * * @Param AccessToken * 공인 토큰 * @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); // 제출 된 매개 변수 treemap <string, list <uploadnewsmedia >> dataparams = new treemap <string, list <uploadnewsmedia >> (); dataparams.put ( "기사", 엔티티); 문자열 data = jsonutil.tojsonstring (dataparams); String JSON = httprequtil.httpsdefaultexecute (SystemConfig.post_method, wechatconfig.upload_forever_news_media_url, params, data); 결과 = jsonutil.fromjsonstring (json, uploadmediasresult.class); 반환 결과; }4. 문자 메시지에 사진을 업로드하여 URL을 얻습니다.
인터페이스 : https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=access_token
이 인터페이스에 업로드 된 그림은 공식 계정의 자료 라이브러리에서 5,000 장의 사진 한계를 차지하지 않습니다. 이미지는 JPG/PNG 형식 만 지원하며 크기는 1MB 미만이어야합니다. 이 인터페이스에서 반환 한 URL은 이미지를 업로드하는 URL이며 문자 메시지에 배치 할 수 있습니다.
/ ** * 문자 메시지에 이미지를 업로드하여 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); 문자열 url = null; try {String json = httpsuploadmediafile (SystemConfig.post_method, wechatconfig.upload_img_media_url, params, path); url = jsonutil.fromjsonstring (json, "url"); } catch (예외 e) {e.printstacktrace (); } 반환 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); 문자열 url = null; try {string json = httpsuploadmedia (SystemConfig.post_method, wechatconfig.upload_img_media_url, params, path, 0, 0); url = jsonutil.fromjsonstring (json, "url"); } catch (예외 e) {e.printstacktrace (); } 반환 URL; }V. 일부 도구
구성 클래스
public static final string upload_img_media_url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg"; 공개 정적 최종 문자열 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"; 공개 정적 최종 문자열 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 {개인 문자열 유형; // 이미지 (이미지), 음성 (음성), 비디오 (비디오) 및 축소판 (썸네일)을 포함한 미디어 파일 유형, 횟수는 뉴스, 즉 개인 문자열 media_id; // 미디어 파일/고유 식별자가 그래픽 및 문자 메시지를 업로드 한 후 얻은 고유 식별자 개인 문자열 생성 _AT; // 미디어 파일 업로드 시간}그래픽 및 문자 메시지 자료 엔터티 클래스를 업로드하십시오
package com.phil.wechat.msg.model.media; java.io.serializable import; / *** 그래픽 메시지 자료 엔티티 클래스 업로드* @Author Phil* @Date 2017 년 9 월 20 일*/ 공개 클래스 업로드 NewSmedia는 직렬화 가능한 {private static final long serialversionuid = 6551817058101753854L; 개인 문자열 whumb_media_id; // 그래픽 메시지의 썸네일의 Media_id는 기본 지원 Upload 멀티미디어 파일 인터페이스에서 개인 문자열 작성자를 얻을 수 있습니다. // 그래픽 메시지 개인 문자열 제목의 저자; // 그래픽 메시지의 제목 개인 문자열 content_source_url; // 링크를 클릭하여 원본 텍스트 개인 문자열 내용을 읽습니다. // 그래픽 메시지 페이지의 내용은 HTML 태그 개인 문자열 다이제스트를 지원합니다. // 그래픽 메시지 설명 개인 int show_conver_pic; // 표지로 표시되는지 여부는 표지 0이 표지로 표시되지 않음으로 표시됩니다}}업로드 방법
/** * 미디어 파일을 업로드 * @param 메소드 * 요청 메소드 get/post * @param path * api path * @param param * api 매개 변수 * @param mediapath * @return * @throws 예외 */public static string httpsuploadmediafile (문자열, 문자열, 매개 변수); url url = new URL (setParmas (param, path, ""); 출력 스트림 출력 = NULL; datainputStream inputStream = null; try {file file = new File (mediapath); if (! file.isfile () ||! file.exists ()) {new ioException ( "파일이 존재하지 않음"); } httpurlConnection con = (httpurlConnection) url.openConnection (); con.setdoinput (true); con.setdooutput (true); con.setUecaches (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); // 텍스트 정보 요청 // 1 부 출력 = 새 DataOutputStream (con.getOutputStream ()); ioutils.write (( "-" + boundary + "/r/n").getBytes(systemConfig.default_character_encoding), 출력); ioutils.write (( "content-dasposition; form-data; name =/"media/"; filename =/" " + file.getName () +"/"/r/n") .getBytes (SystemConfig.default_character_encoding), 출력); ioutils.write ( "content-type : application/octet-stream/r/n/r/n".getBytes (SystemConfig.default_character_encoding), 출력); // ioutils.write (( "content-type :" + fileExt + "/r/n/r/n"). getBytes (), 출력); // 파일 바디 파트 // 파일을 스트리밍하여 파일을 URL로 밀어 넣습니다. inputStream = new DataInputStream (새 fileInputStream (file)); ioutils.copy (입력 스트림, 출력); // part ioutils.write (( "/r/n--" + boundary + "-/r/n"). getBytes (SystemConfig.default_character_encoding), 출력); output.flush (); 결과 = inputStreamToString (con.getInputStream ()); } catch (marlomedurlexception e) {e.printstacktrace (); } catch (protocolexception e) {e.printstacktrace (); } catch (ioException e) {Throw new ioException ( "데이터 오류 읽기"); } 마침내 {ioutils.closequietly (출력); ioutils.closequietly (inputstream); } 반환 결과; }/** * 미디어 파일을 업로드 할 수 없습니다 (로컬) * @param 메소드 * @param 메소드 * @param path * @param path * @pi path * @param param * api parameter * @param mediapath * @param mediapath * @param conntime * @param readtime * @param readtime * @throw string * @th rows는 기본값 */retrow입니다. httpsuploadmedia (문자열 메소드, 문자열 경로,지도 <문자열, 문자열> param, String mediapath, int conntime, int readtime) 예외 {string result = ""; url url = new URL (setParmas (param, path, ""); 출력 스트림 출력 = NULL; bufferedInputStream inputStream = null; try {String boundary = "----"; httpurlconnection conn = getConnection (메소드, 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.setUcaches (False); MediaConn.setRequestMethod (SystemConfig.get_Method); MediaConn.setConnectTimeout (conntime == 0? default_conntime : conntime); MediaConn.setReadTimeout (readtime == 0? default_upload_readtime : readtime); 문자열 conntype = mediaconn.getContentType (); // 파일 확장자 get string fileExt = getFileExt (Conntype); ioutils.write (( "-" + boundary + "/r/n"). getBytes (), 출력); ioutils.write (( "Content-Disposition : form-data; name =/"media/"; filename =/" " + getfilename (mediapath) +"/"/r/n"). getBytes (), 출력); ioutils.write (( "content-type :" + fileext + "/r/n/r/n"). getBytes (), 출력); inputStream = new bufferedInputStream (mediaConn.getInputStream ()); ioutils.copy (입력 스트림, 출력); ioutils.write (( "/r/n ----" + boundary + "-/r/n"). getBytes (), 출력); mediaconn.disconnect (); // 입력 스트림 얻기 결과 = inputStreamToString (conn.getInputStream ()); }} catch (marformedurlexception e) {e.printstacktrace (); } catch (protocolexception e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); } 마침내 {ioutils.closequietly (출력); ioutils.closequietly (inputstream); } 반환 결과; }/** * 비디오 미디어 파일 업로드 * * @param 메소드 * 요청 메소드 get/post * @param path * api path * @param param * api 매개 변수 * @param mediapath * @param mediapath * @param 제목 * @param 제목 * @param 소개 * @Throws Exception */public strows httpupload, (string) Map <String, String> Param, String MediaPath, String Title, String 소개) 예외 {String result = null; url url = new URL (setParmas (param, path, ""); 출력 스트림 출력 = NULL; datainputStream inputStream = null; try {file file = new File (mediapath); if (! file.isfile () ||! file.exists ()) {new ioException ( "파일이 존재하지 않음"); } httpurlConnection con = (httpurlConnection) url.openConnection (); con.setdoinput (true); con.setdooutput (true); con.setUecaches (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); // 신체 정보 요청 // 1 부 출력 = 새 DataOutputStream (con.getOutputStream ()); ioutils.write (( "-" + boundary + "/r/n").getBytes(systemConfig.default_character_encoding), 출력); ioutils.write (( "Content-Disposition : form-data; name =/"media/"; filename =/" " + file.getName () +"/"/r/n") .getBytes (), 출력); ioutils.write ( "content-type : video/mp4/r/n/r/n".getBytes (), 출력); // 파일 바디 파트 // 파일을 스트리밍하여 파일을 URL로 밀어 넣습니다. inputStream = new DataInputStream (새 fileInputStream (file)); ioutils.copy (입력 스트림, 출력); // part ioutils.write (( "-" + boundary + "/r/n").getBytes(systemConfig.default_character_encoding), 출력); ioutils.write ( "내용화 : form-data; name =/"description/";/r/n/r/n".getBytes (SystemConfig.default_character_encoding), 출력); ioutils.write (( "{/"title/":/" " + title +"/",/"소개/":/" " + 소개 +"/"}") ioutils.write (( "/r/n--" + boundary + "). output.flush (); 결과 = inputStreamToString (con.getInputStream ()); } catch (marlomedurlexception e) {e.printstacktrace (); } catch (protocolexception e) {e.printstacktrace (); } catch (ioException e) {Throw new ioException ( "데이터 오류 읽기"); } 마침내 {ioutils.closequietly (출력); ioutils.closequietly (inputstream); } 반환 결과; } /** * 비디오 미디어 파일 (네트워크) * * @param 메소드 * @param method * @param path * @param path * @param path * @param param * api 매개 변수 * @param mediapath * @param mediapath * @param 제목 * @param 제목 * 비디오 제목 * @partam 소개 * @param conntime * @param readtime * @param 읽기 * @param 읽기 * @throws Exception */ public static String httpsuploadvideomedia (문자열 메서드, 문자열 경로, 맵 <문자열, 문자열> 매개 변수, 문자열 mediapath, 문자열 제목, 문자열 소개, int conntime, int readtime) {string result = null; url url = new URL (setParmas (param, path, ""); 출력 스트림 출력 = NULL; bufferedInputStream inputStream = null; try {String boundary = "----"; httpurlconnection conn = getConnection (메소드, 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.setUcaches (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 (), 출력); ioutils.write (( "Content-Disposition : form-data; name =/"media/"; filename =/" " + getfilename (mediapath) +"/"/r/n"). getBytes (), 출력); ioutils.write ( "content-type : video/mp4/r/n/r/n".getBytes (), 출력); inputStream = new bufferedInputStream (mediaConn.getInputStream ()); ioutils.copy (입력 스트림, 출력); // part ioutils.write (( "-" + boundary + "/r/n").getBytes(systemConfig.default_character_encoding), 출력); ioutils.write ( "내용화 : form-data; name =/"description/";/r/n/r/n".getBytes (SystemConfig.default_character_encoding), 출력); ioutils.write (( "{/"title/":/" " + title +"/",/"소개/":/" " + 소개 +"/"}") ioutils.write (( "/r/n--" + boundary + "). mediaconn.disconnect (); // 입력 스트림 얻기 결과 = inputStreamToString (conn.getInputStream ()); }} catch (marformedurlexception e) {e.printstacktrace (); } catch (protocolexception e) {e.printstacktrace (); } catch (ioException e) {Throw new ioException ( "데이터 오류 읽기"); } 마침내 {ioutils.closequietly (출력); ioutils.closequietly (inputstream); } 반환 결과; }위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.