Java micro-letter development upload Download multimedia file _php instance

Source: Internet
Author: User
Tags readline stringbuffer

Reply pictures, audio, video messages are needed media_id, this is the need to upload multimedia files to the micro-trust server.

Upload multimedia files to the micro-trust server, as well as download files from the micro-mail server, you can refer to: http://mp.weixin.qq.com/wiki/index.php?title= uploading and downloading multimedia files

The method of uploading and downloading multimedia files is still written in 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 = "21441e9f3226eee81e14380a768b6d1e"; Gets the Access_token interface address (get) limit of 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 public final static map<string,object> Accesstokenmap = new hashmap<string,
 Object> (); /** * Initiates HTTPS request and obtains results * * @param requesturl Request address * @param Requestmethod request (GET, POST) * @param outputstr submitted data * @r Eturn Jsonobject (Jsonobject.get (key) to get the property value of the JSON object)/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);
  } 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 Getaccesstok
 En (String appid,string appsecret) {Accesstoken at = new Accesstoken (); Each time a access_token is obtained, it is obtained from the Accesstokenmap, and if it is expired, it is retrieved from the micro-credit and has no expiration direct return//The validity of the token obtained from the micro-letter 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 ("token not expired in cache, get Access_token directly from cache");
  The token is not expired and returns a string token = (string) accesstokenmap.get ("token") directly from the 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);
 After each fetch Access_token, deposit ACCESSTOKENMAP//Next fetch, if not expired 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 (String.Format) (menu creation failed!)
  Errorcode:%d,errormsg:%s ", Jsonobject.getint (" Errcode "), Jsonobject.getstring (" errmsg "));
 return false; Log.info (menu creation succeeded!)
 
 ");
 return true; //Upload multimedia files to the micro-server public static final String Upload_media_url = "Http://file.api.weixin.qq.com/cgi-bin/media/upload?a
 Ccess_token=access_token&type=type "; /** * Upload multimedia files to micro-mail server <br> * @see http://www.oschina.net/code/snippet_1029535_23824 * @see http://mp.weixin.qq.com/ wiki/index.php?title= Upload Download Multimedia file * * @author QINCD * @date Nov 6, 2014 4:11:22 PM/public static Jsonobject uploadmed IATOWX (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");
    Sets the boundary String boundary = "----------" + system.currenttimemillis (); Conn.setrequestproperty ("Content-type", "multipart/form-data;
 
    boundary= "+ boundary);
    Request body information//The 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 ();
 
    The end part byte[] foot = ("\r\n--" + boundary + "--\r\n"). GetBytes ("Utf-8");//define the last data divider 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 STR
     Ingbuffer ();
     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&AMP;MEDIA_ID=MEDIA_ID "; /** * Download multimedia files from micro-servers * * @author QINCD * @date Nov 6, 2014 4:32:12 PM/public static String downloadmediafromwx (Str ing accesstoken,string mediaid,string filesavepath) throws IOException {if (stringutils.isempty) | |
 
 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, 2014 9:57:54 AM */public static void main (Stri Ng[] 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 picture failed");
 Return
 int errcode = 0;
 if (Uploadjsonobj.containskey ("Errcode")) {Errcode = Uploadjsonobj.getint ("Errcode");
  
  } if (Errcode = 0) {System.out.println ("picture upload succeeded");
  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 micro-letter * * @author QINCD * @date Nov 6, 2014 4:15:14 PM/public static Jsonobject Testuploadmedia (S
 Tring filepath,string type,string accesstoken) {try {return weixinutil.uploadmediatowx (FilePath, type, accesstoken);
 catch (IOException e) {e.printstacktrace ();
 return null; /** * Download multimedia file from micro-letter * * @author QINCD * @date Nov 6, 2014 4:56:25 PM/public static String Testdownloadmedia (Str ing accesstoken,string mediaid,string filesavedir) {try {return weixinutil.downloadmediafromwx Accesstoken, MediaId,
 FILESAVEDIR);
 catch (IOException e) {e.printstacktrace ();
 return null;
 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.