微信企業號上傳下載多媒體檔案介面詳解示範-java,上傳下載-java

來源:互聯網
上載者:User

企業號上傳下載多媒體檔案介面詳解示範-java,上傳下載-java

講完這篇部落格,企業號的介面就說完了,下載了我源碼的童鞋都知道,裡面的備忘很詳細,但凡看過幾遍就都會自己開發了,我說的這些介面至此我已經全部開發完了,剩下的就是你們自己寫功能了,都是輕而易舉事情了,我可能後期會主要放在Android上了,屆時歡迎大家進來一起探討,一起學習噢,謝謝

企業在使用介面時,對多媒體檔案、多媒體訊息的擷取和調用等操作,是通過media_id來進行的。通過本介面,企業可以上傳或下載多媒體檔案。


注意,每個多媒體檔案(media_id)會在上傳到伺服器3天后自動刪除,以節省伺服器資源


上傳媒體檔案:

/** * 上傳媒體檔案 * @param accessToken 介面訪問憑證 * @param type 媒體檔案類型,分別有圖片(image)、語音(voice)、視頻(video),普通檔案(file) * @param media form-data中媒體檔案標識,有filename、filelength、content-type等資訊 * @param mediaFileUrl 媒體檔案的url * 上傳的媒體檔案限制     * 圖片(image):1MB,支援JPG格式     * 語音(voice):2MB,播放長度不超過60s,支援AMR格式     * 視頻(video):10MB,支援MP4格式     * 普通檔案(file):10MB * */public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {WeixinMedia weixinMedia = null;// 拼裝請求地址String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);// 定義資料分隔字元String boundary = "------------7da2e536604c8";try {URL uploadUrl = new URL(uploadMediaUrl);HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();uploadConn.setDoOutput(true);uploadConn.setDoInput(true);uploadConn.setRequestMethod("POST");// 佈建要求頭Content-TypeuploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);// 擷取媒體檔案上傳的輸出資料流(往伺服器寫資料)OutputStream outputStream = uploadConn.getOutputStream();URL mediaUrl = new URL(mediaFileUrl);HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();meidaConn.setDoOutput(true);meidaConn.setRequestMethod("GET");// 從要求標頭中擷取內容類型String contentType = meidaConn.getHeaderField("Content-Type");// 根據內容類型判斷副檔名String fileExt = WeixinUtil.getFileEndWitsh(contentType);// 請求體開始outputStream.write(("--" + boundary + "\r\n").getBytes());outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());// 擷取媒體檔案的輸入資料流(讀取檔案)BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());byte[] buf = new byte[8096];int size = 0;while ((size = bis.read(buf)) != -1) {// 將媒體檔案寫到輸出資料流(往伺服器寫資料)outputStream.write(buf, 0, size);}// 請求體結束outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());outputStream.close();bis.close();meidaConn.disconnect();// 擷取媒體檔案上傳的輸入資料流(從伺服器讀資料)InputStream inputStream = uploadConn.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);StringBuffer buffer = new StringBuffer();String str = null;while ((str = bufferedReader.readLine()) != null) {buffer.append(str);}bufferedReader.close();inputStreamReader.close();// 釋放資源inputStream.close();inputStream = null;uploadConn.disconnect();// 使用JSON-lib解析返回結果JSONObject jsonObject = JSONObject.fromObject(buffer.toString());// 測試列印結果System.out.println("列印測試結果"+jsonObject);weixinMedia = new WeixinMedia();weixinMedia.setType(jsonObject.getString("type"));// type等於 縮圖(thumb) 時的返回結果和其它類型不一樣if ("thumb".equals(type))weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));elseweixinMedia.setMediaId(jsonObject.getString("media_id"));    weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));} catch (Exception e) {weixinMedia = null;String error = String.format("上傳媒體檔案失敗:%s", e);System.out.println(error);}return weixinMedia;}

下載媒體檔案:

/** * 擷取媒體檔案 * @param accessToken 介面訪問憑證 * @param media_id 媒體檔案id * @param savePath 檔案在伺服器上的儲存路徑 * */public static String downloadMedia(String accessToken, String mediaId, String savePath) {String filePath = null;// 拼接請求地址String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);System.out.println(requestUrl);try {URL url = new URL(requestUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setDoInput(true);conn.setRequestMethod("GET");if (!savePath.endsWith("/")) {savePath += "/";}// 根據內容類型擷取副檔名String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));// 將mediaId作為檔案名稱filePath = savePath + mediaId + fileExt;BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());FileOutputStream fos = new FileOutputStream(new File(filePath));byte[] buf = new byte[8096];int size = 0;while ((size = bis.read(buf)) != -1)fos.write(buf, 0, size);fos.close();bis.close();conn.disconnect();String info = String.format("下載媒體檔案成功,filePath=" + filePath);System.out.println(info);} catch (Exception e) {filePath = null;String error = String.format("下載媒體檔案失敗:%s", e);System.out.println(error);}return filePath;}

main 樣本:

 //樣本public static void main(String[] args) {/** * 上傳多媒體檔案 */String access_token = WeixinUtil.getAccessToken(ParamesAPI.corpId, ParamesAPI.secret).getToken();//地址WeixinMedia weixinMedia = uploadMedia(access_token, "image", "http://localhost:8080/weixinClient/images/weather3.jpg");//media_idSystem.out.println("media_id:"+weixinMedia.getMediaId());//類型System.out.println("類型:"+weixinMedia.getType());//時間戳記System.out.println("時間戳記:"+weixinMedia.getCreatedAt());//列印結果if(null!=weixinMedia){System.out.println("上傳成功!");}else{System.out.println("上傳失敗!");}System.out.println("分割線*******************************************************************************************");/** * 下載多媒體檔案 */String savePath = downloadMedia(access_token, weixinMedia.getMediaId(), "E:/download");System.out.println("下載成功之後儲存在本地的地址為:"+savePath);}

本地測試列印結果圖:



下載成功之後儲存到本地的圖片地址圖片:



OK,至此介面就全部說完了,祝大伙兒跟著源碼和我的部落格學習,全部可以獨立開發,成為開發神人啊,嘿嘿,謝謝!



開發平台中有個介面是上傳多媒體檔案,我用的是java 開發的,我怎才可以在後台實現?代碼如下:

/** * 檔案上傳到伺服器 * @param fileType 檔案類型 * @param filePath 檔案路徑 * @return JSONObject * @throws Exception */ public static JSONObject send(String fileType, String filePath) throws Exception { String result = null; File file = new File(filePath); if (!file.exists() || !file.isFile()) { throw new IOException("檔案不存在"); } /** * 第一部分 */ URL urlObj = new URL("file.api.weixin.qq.com/...token="+ getAccess_token() + "&type="+fileType+""); HttpURLConnection con = (HttpURLConnection) urlObj.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"); // 設定邊界 String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY); // 請求本文資訊 // 第一部分: StringBuilder sb = ......餘下全文>>
 
java發布服務,通過介面查看多媒體檔案有什方法可以實現這個功可以,解答

Web Service嗎?
用soap協議(底層XML傳輸)傳輸效率肯定大打折扣。
只能用二進位傳輸了,java背景話,可以用hessian的二進位傳輸協議。不hessian我還真沒用過,你可以在網上查一下,配置應該都差不多給你幾個連結:
1、www.iteye.com/topic/14887 用spirng和hessian構建分布式應用(遠程介面)的方法
2、hessian.caucho.com/ hessian官網
多媒體形式,其實Adobe的AMF(相當於Web service)協議亦可以考慮一下,不過就是不知道蘋果支援不支援,蘋果裝置上不支援Flash。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.