In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "java Wechat development how to upload and download multimedia files", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "java Wechat development how to upload and download multimedia files" this article.
The code is as follows:
Import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.SecureRandom Import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.Map;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import net.sf.json.JSONObject;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import com.company.project.model.menu.AccessToken;import com.company.project.model.menu.Menu Public class WeixinUtil {private static Logger log = Logger.getLogger (WeixinUtil.class); public final static String APPID = "wxb927d4280e6db674"; public final static String APP_SECRET = "21441e9f3226eee81e14380a768b6d1e"; / / get the interface address (GET) of access_token. Public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";. / / create menu public final static String create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; / / Store: 1. TokenPerson2: time to get token, 3. Expiration time public final static Map accessTokenMap = new HashMap (); / * * initiate a https request and get the result * * @ param requestUrl request address * @ param requestMethod request method (GET, POST) * @ data submitted by param outputStr * @ return JSONObject (get the property value of the json object through JSONObject.get (key)) * / public static JSONObject handleRequest (String requestUrl,String requestMethod,String outputStr) {JSONObject jsonObject = null Try {URL url = new URL (requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection (); SSLContext ctx = SSLContext.getInstance ("SSL", "SunJSSE"); TrustManager [] tm = {new MyX509TrustManager ()}; ctx.init (null, tm, new SecureRandom ()); SSLSocketFactory sf = ctx.getSocketFactory (); conn.setSSLSocketFactory (sf); conn.setDoInput (true); conn.setDoOutput (true); conn.setRequestMethod (requestMethod); conn.setUseCaches (false); if ("GET" .equalsIgnoreCase (requestMethod)) {conn.connect () } if (StringUtils.isNotEmpty (outputStr)) {OutputStream out = conn.getOutputStream (); out.write (outputStr.getBytes ("utf-8")); out.close ();} InputStream in = conn.getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (in, "utf-8")); StringBuffer buffer = new StringBuffer (); String line = null; while ((line = br.readLine ())! = null) {buffer.append (line);} in.close (); conn.disconnect () JsonObject = JSONObject.fromObject (buffer.toString ());} catch (MalformedURLException e) {e.printStackTrace (); log.error ("URL error!") ;} catch (IOException e) {e.printStackTrace ();} catch (NoSuchAlgorithmException e) {e.printStackTrace ();} catch (NoSuchProviderException e) {e.printStackTrace ();} catch (KeyManagementException e) {e.printStackTrace ();} return jsonObject;} / * * obtain access_token * * @ author qincd * @ date Nov 6, 2014 9:56:43 AM * / public static AccessToken getAccessToken (String appid,String appSecret) {AccessToken at = new AccessToken () / / every time you get an access_token, get it from accessTokenMap first. If it expires, get it again from Wechat / / return directly without expiration / the token obtained from Wechat is valid for 2 hours if (! accessTokenMap.isEmpty ()) {Date getTokenTime = (Date) accessTokenMap.get ("getTokenTime"); Calendar c = Calendar.getInstance (); c.setTime (getTokenTime); c.add (Calendar.HOUR_OF_DAY, 2); getTokenTime = c.getTime () If (getTokenTime.after (new Date () {log.info ("get access_token directly from cache if token has not expired in cache"); / / if token is not expired, return String token = (String) accessTokenMap.get ("token") directly from cache; Integer expire = (Integer) accessTokenMap.get ("expire"); at.setToken (token); at.setExpiresIn (expire); return at } String requestUrl = access_token_url.replace ("APPID", appid) .replace ("APPSECRET", appSecret); JSONObject object = handleRequest (requestUrl, "GET", null); String access_token = object.getString ("access_token"); int expires_in = object.getInt ("expires_in"); log.info ("\ naccess_token:" + access_token); log.info ("\ nexpires_in:" + expires_in); at.setToken (access_token) At.setExpiresIn (expires_in); / / every time you get an access_token, deposit it in accessTokenMap / / the next time you get it, if it doesn't expire, it will be fetched directly from accessTokenMap. AccessTokenMap.put ("getTokenTime", new Date ()); accessTokenMap.put ("token", access_token); accessTokenMap.put ("expire", expires_in); return at;} / * * create menu * * @ author qincd * @ date Nov 6, 2014 9:56:36 AM * / public static boolean createMenu (Menu menu,String accessToken) {String requestUrl = create_menu_url.replace ("ACCESS_TOKEN", accessToken); String menuJsonString = JSONObject.fromObject (menu). ToString () JSONObject jsonObject = handleRequest (requestUrl, "POST", menuJsonString); String errorCode = jsonObject.getString ("errcode"); if (! "0" .equals (errorCode)) {log.error (menu creation failed! ErrorCode:%d,errorMsg:%s ", jsonObject.getInt (" errcode "), jsonObject.getString (" errmsg ")); return false;} log.info (" menu created successfully! ") ; return true;} / / upload multimedia files to Wechat server public static final String upload_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; / * upload multimedia files to Wechat server
* @ see http://www.oschina.net/code/snippet_1029535_23824 * @ see http://mp.weixin.qq.com/wiki/index.php?title= upload and download multimedia files * * @ author qincd * @ date Nov 6, 2014 4:11:22 PM * / public static JSONObject uploadMediaToWX (String filePath,String type,String accessToken) throws IOException {File file = new File (filePath); if (! file.exists ()) {log.error ("File does not exist!") ; return null;} String url = upload_media_url.replace ("ACCESS_TOKEN", accessToken) .replace ("TYPE", type); URL urlObj = new URL (url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection (); conn.setDoInput (true); conn.setDoOutput (true); conn.setUseCaches (false); conn.setRequestProperty ("Connection", "Keep-Alive"); conn.setRequestProperty ("Charset", "UTF-8") / / set the boundary String BOUNDARY = "-" + System.currentTimeMillis (); conn.setRequestProperty ("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); / / request body information / / part I: StringBuilder sb = new StringBuilder (); sb.append ("- -"); / / must have more than two lines sb.append (BOUNDARY) Sb.append ("\ r\ n"); sb.append ("Content-Disposition: form-data;name=\" file\ "; filename=\" + file.getName () + "\"\ r\ n "); sb.append (" Content-Type:application/octet-stream\ r\ n\ r\ n "); byte [] head = sb.toString (). GetBytes (" utf-8 "); / / get the output stream OutputStream out = new DataOutputStream (conn.getOutputStream ()) Out.write (head); / / the body of the file DataInputStream in = new DataInputStream (new FileInputStream (file)); int bytes = 0; byte [] bufferOut = new byte [1024]; while ((bytes = in.read (bufferOut))! =-1) {out.write (bufferOut, 0, bytes);} in.close () / / ending part byte [] foot = ("\ r\ nmura -" + BOUNDARY + "- -\ r\ n") .getBytes ("utf-8"); / / define the final data separator line out.write (foot); out.flush (); out.close () / * the server response must be read, otherwise the submission will not succeed * / try {/ / define the BufferedReader input stream to read the URL response StringBuffer buffer = new StringBuffer (); BufferedReader reader = new BufferedReader (new InputStreamReader (conn.getInputStream (); String line = null; while ((line = reader.readLine ())! = null) {buffer.append (line);} reader.close () Conn.disconnect (); return JSONObject.fromObject (buffer.toString ());} catch (Exception e) {log.error ("an exception occurred sending a POST request!" + e); e.printStackTrace ();} return null;} public static final String download_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; / * download multimedia files from Wechat server * * @ author qincd * @ date Nov 6, 2014 4:32:12 PM * / public static String downloadMediaFromWx (String accessToken,String mediaId,String fileSavePath) throws IOException {if (StringUtils.isEmpty (accessToken) | | StringUtils.isEmpty (mediaId)) return null; String requestUrl = download_media_url.replace ("ACCESS_TOKEN", accessToken) .replace ("MEDIA_ID", mediaId); URL url = new URL (requestUrl) HttpURLConnection conn = (HttpURLConnection) url.openConnection (); conn.setRequestMethod ("GET"); conn.setDoInput (true); conn.setDoOutput (true); InputStream in = conn.getInputStream (); File dir = new File (fileSavePath); if (! dir.exists ()) {dir.mkdirs ();} if (! fileSavePath.endsWith ("/")) {fileSavePath + = "/";} String ContentDisposition = conn.getHeaderField ("Content-disposition") String weixinServerFileName = ContentDisposition.substring (ContentDisposition.indexOf ("filename") + 10, ContentDisposition.length ()-1); fileSavePath + = weixinServerFileName; BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (fileSavePath)); byte [] data = new byte [1024]; int len =-1; while ((len = in.read (data))! =-1) {bos.write (data,0,len);} bos.close (); in.close (); conn.disconnect (); return fileSavePath;}}
Test the code:
Public class WeixinUtilTest {/ * * @ author qincd * @ date Nov 6, 2014 9:57:54 AM * / public static void main (String [] args) {/ / 1) Get access_token AccessToken accessToken = WeixinUtil.getAccessToken (WeixinUtil.APPID, WeixinUtil.APP_SECRET); String filePath = "C:\\ Users\\ qince\\ Pictures\\ wallpaper 20141029091612.jpg"; JSONObject uploadJsonObj = testUploadMedia (filePath, "image", accessToken.getToken ()); if (uploadJsonObj = = null) {System.out.println ("upload failed"); return;} int errcode = 0; if (uploadJsonObj.containsKey ("errcode")) {errcode = uploadJsonObj.getInt ("errcode") } if (errcode = = 0) {System.out.println ("picture uploaded successfully"); String mediaId = uploadJsonObj.getString ("media_id"); long createAt = uploadJsonObj.getLong ("created_at"); System.out.println ("--Details:"); System.out.println ("media_id:" + mediaId); System.out.println ("created_at:" + createAt);} else {System.out.println ("picture upload failed!") ; String errmsg = uploadJsonObj.getString ("errmsg"); System.out.println ("--Details:"); System.out.println ("errcode:" + errcode); System.out.println ("errmsg:" + errmsg);} String mediaId = "6W-UvSrQ2hkdSdVQJJXShwtFDPLfbGI1qnbNFy8weZyb9Jac2xxxcAUwt8p4sYPH"; String filepath = testDownloadMedia (accessToken.getToken (), mediaId, "d:/test"); System.out.println (filepath) } / * upload multimedia files to Wechat * * @ author qincd * @ date Nov 6, 2014 4:15:14 PM * / public static JSONObject testUploadMedia (String filePath,String type,String accessToken) {try {return WeixinUtil.uploadMediaToWX (filePath, type, accessToken);} catch (IOException e) {e.printStackTrace ();} return null } / * download multimedia files from Wechat * * @ author qincd * @ date Nov 6, 2014 4:56:25 PM * / public static String testDownloadMedia (String accessToken,String mediaId,String fileSaveDir) {try {return WeixinUtil.downloadMediaFromWx (accessToken, mediaId, fileSaveDir);} catch (IOException e) {e.printStackTrace ();} return null }} these are all the contents of the article "how to upload and download Multimedia Files in the Development of java Wechat". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.