WeChat java generic version download Java WeChat development upload download multimedia file

Source: Internet
Author: User
The reply picture, the audio, the video message all need media_id, this is needs to upload the multimedia file to the server only.

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

The way to upload and download multimedia files is to write 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 f inal static String APPID = "wxb927d4280e6db674"; Public final static String App_secret = "21441e9f3226eee81e14380a768b6d1e"; Get Access_token interface Address (get) 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: Time to get token, 3. Expiration time public final static Map
 
  
 Accesstokenmap = new HashMap 
  
   
(); /** * Initiate HTTPS request and get results * * @param requesturl Request address * @param Requestmethod request (GET, POST) * @param outputstr submitted data * @return Jsonobject (key) to get the value of the JSON object's property (jsonobject.get) */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 (Nosuch ProviderException e) {e.printstacktrace ()} catch (Keymanagementexception e) {e.printstacktrace ();} return Jsonobjec T }/** * Get Access_token * * @author QINCD * @date Nov 6, 9:56:43 AM */public static Accesstoken Getaccesstoken (Strin The period is returned directly//from the token that is obtained 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 ("The token found in the cache has not expired, get Access_token directly from the cache");  Token does not expire and gets returned directly from the cache String token = (string) accesstokenmap.get ("token");  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); After each acquisition of Access_token, deposit Accesstokenmap//Next fetch, if no expiration is taken 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, 9:56:36 AM */public static Boolean CreateMenu (menu menu,string Access Token) {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 multimedia file to server public static final String Upload_media_url = "Http://file.api.weixin.qq.com/cgi-bin/media/upload?" Access_token=access_token&type=type "; /** * Uploading 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 and download multimedia files * * @author QINCD * @date Nov 6, 4:11:22 PM */public static jsonobject uploadmediatowx (String filepath,str ing type,string accesstoken) throws ioexception{File File = new file (FilePath), if (!file.exists ()) {log.error ("file does not exist!) "); return null; The 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//First part: StringBuilder SB = new StringBuilder (); Sb.append ("--"); // Must be 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 output stream OutputStream out = new DataOutputStream (Conn.getoutputstream ()); Out.write (head); File body part 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 (); End part byte[] foot = ("\r\n--" + boundary + "--\r\n"). GetBytes ("Utf-8");//define the last data separation line out.write (foot); Out.flush (); Out.close (); /** * Read server response, must read, otherwise commit unsuccessful */try {//define BufferedReader input stream to read URL response stringbuffer buffer = new Stringbu Ffer (); 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 ("send POST request exception! "+ 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 the server * * @author QINCD * @date Nov 6, 4:32:12 PM */public static string Downloadmediafromwx (String acce Sstoken,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 code:

public class Weixinutiltest {/** * * @author QINCD * @date Nov 6, 9:57:54 AM */public static void Main (string[] Arg s) {//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 image failed"); Return } int errcode = 0; if (Uploadjsonobj.containskey ("Errcode")) {Errcode = Uploadjsonobj.getint ("Errcode");} if (Errcode = = 0) {System.out.    println ("Image upload success");  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 * * @author QINCD * @date 6, 4:15:14 PM */public static jsonobject Testuploadmedia (String filep Ath,string type,string Accesstoken) {try {return weixinutil.uploadmediatowx (FilePath, type, accesstoken);} catch (Ioex  Ception e) {e.printstacktrace ();} return null; /** * from downloading multimedia files * * @author QINCD * @date Nov 6, 4:56:25 PM */public static string Testdownloadmedia (String access Token,string mediaid,string Filesavedir) {try {return weixinutil.downloadmediafromwx (Accesstoken, MediaId, FILESAVEDIR);  } catch (IOException e) {e.printstacktrace ();} return null; }}

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support this site.

The above describes the Java general download Java development upload download multimedia files, including the Java general download content, I hope the PHP tutorial interested in a friend helpful.

  • 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.