Java WeChat development-uploading and downloading multimedia file _ php instance

Source: Internet
Author: User
This article describes in detail how to upload and download multimedia files through java development, if you are interested, you can refer to the scenarios where media_id is required to reply images, audios, and video messages. Therefore, you must Upload multimedia files to the server.

To upload multimedia files to the server and download files from the server, see: http://mp.weixin.qq.com/wiki/index.php? Title = upload and download multimedia files

The method for uploading and downloading multimedia files is still written to WeixinUtil. java.

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 = "secret"; // GET access_token interface address (GET) is limited to 200 times/day) 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 "; // Storage: 1. token, 2: Get token time, 3. expiration time public final static Map
 
  
AccessTokenMap = new HashMap
  
   
();/*** Initiate an https request and obtain the result ** @ param requestUrl request address * @ param requestMethod request method (GET and POST) * @ param outputStr data submitted * @ return JSONObject (through JSONObject. get (key) method to get the json object attribute value) */public static JSONObject handleRequest (String requestUrl, String requestMethod, String outputStr) {JSONObject jsonObject = null; try {URL url = new URL (requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url. openConn Ection (); 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. connec T ();} 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;}/*** get access_token ** @ author qincd * @ date Nov 6, 2014 9:56:43 AM */public static AccessToken getAccessToken (String appid, string appSecret) {Acc EssToken at = new AccessToken (); // Obtain the access_token from accessTokenMap each time, if the token expires, the token is returned immediately after the token expires. // 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 ("the token in the cache has not expired, and the access_token is directly obtained from the cache"); // The token has not expired, the String token = (String) accessTokenMap is returned directly from the cache. get ("token"); Integer expire = (Integer) AccessTokenMap. get ("expire");. setToken (token);. setExpiresIn (expire); return at ;}} String requestUrl = access_token_url.replace ("APPID", appid ). replace ("APPSECRET", appSecret); JSONObject = 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);. setToken (access_token);. setExpiresIn (expires_in); // after each access_token is obtained, it is saved to the accessTokenMap. // if it does not expire, it is directly obtained from the 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 (String. format ("menu creation failed! ErrorCode: % d, errorMsg: % s ", jsonObject. getInt ("errcode"), jsonObject. getString ("errmsg"); return false;} log.info ("menu created successfully! "); Return true;} // upload the multimedia file to the 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 the server
   
* @ See http://www.oschina.net/code/snippet_1029535_23824 * @ See http://mp.weixin.qq.com/wiki/index.php?title= Upload/download a multimedia file ** @ author qincd * @ date Nov 6, 2014 4:11:22 */public static JSONObject uploadMediaToWX (String filePath, String type, String accessToken) throws IOException {File file = new File (filePath); if (! File. exists () {log. error ("The 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 1: StringBuilder sb = new StringBuilder (); sb. append ("--"); // there must be two more lines of 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 "); byte [] head = sb. toString (). getBytes ("UTF-8"); // get the output stream OutputStream out = new DataOutputStream (conn. getOutputStream (); out. write (head); // 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 (); // the end part of byte [] foot = ("\ r \ n --" + BOUNDARY + "-- \ r \ n "). getBytes ("UTF-8"); // defines the last data separation line out. write (foot); out. flush (); out. close ();/*** READ the server response, which must be read, otherwise, the submission fails */try {// defines the BufferedReader input stream to read the URL response StringBuffer buffer = new StringBuffer (); BufferedReader reader = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line = nul L; 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 when sending the 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 a multimedia file from the server ** @ author qincd * @ date Nov 6, 2014 4:32:12 */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 (requ EstUrl); 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 code:

Public class WeixinUtilTest {/***** @ author qincd * @ date Nov 6, 2014 9:57:54 AM */public static void main (String [] args) {// 1 ). obtain access_token AccessToken accessToken = WeixinUtil. getAccessToken (WeixinUtil. APPID, WeixinUtil. APP_SECRET); String filePath = "C: \ Users \ qince \ Pictures \ wallpaper 201%29091612.jpg"; JSONObject uploadJsonObj = testUploadMedia (filePath, "image", accessToken. getToken (); if (UploadJsonObj = null) {System. out. println ("image Upload failed"); return;} int errcode = 0; if (uploadJsonObj. containsKey ("errcode") {errcode = uploadJsonObj. getInt ("errcode");} if (errcode = 0) {System. out. println ("image uploaded successfully"); String mediaId = uploadJsonObj. getString ("media_id"); long createAt = uploadJsonObj. getLong ("created_at"); System. out. println ("-- Details:"); System. out. println ("media_id:" + media Id); System. out. println ("created_at:" + createAt);} else {System. out. println ("image Upload failed! "); String errmsg = uploadJsonObj. getString ("errmsg"); System. out. println ("-- Details:"); System. out. println ("errcode:" + errcode); System. out. println ("errmsg:" + errmsg);} String mediaId = "inline"; String filepath = testDownloadMedia (accessToken. getToken (), mediaId, "d:/test"); System. out. println (filepath);}/*** Upload a multimedia file to ** @ author qincd * @ date Nov 6, 2014 4:15:14 */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 a multimedia file ** @ 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 ;}}

The above is all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can support your own home.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.