java微信开发之上传下载多媒体文件
回复图片、音频、视频消息都是需要media_id的,这个是需要将多媒体文件上传到微信服务器才有的。
将多媒体文件上传到微信服务器,以及从微信服务器下载文件,可以参考:http://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件
上传下载多媒体文件的方法还是写到WeixinUtil.java中。
代码如下:
importjava.io.BufferedOutputStream; importjava.io.BufferedReader; importjava.io.DataInputStream; importjava.io.DataOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.net.HttpURLConnection; importjava.net.MalformedURLException; importjava.net.URL; importjava.security.KeyManagementException; importjava.security.NoSuchAlgorithmException; importjava.security.NoSuchProviderException; importjava.security.SecureRandom; importjava.util.Calendar; importjava.util.Date; importjava.util.HashMap; importjava.util.Map; importjavax.net.ssl.HttpsURLConnection; importjavax.net.ssl.SSLContext; importjavax.net.ssl.SSLSocketFactory; importjavax.net.ssl.TrustManager; importnet.sf.json.JSONObject; importorg.apache.commons.lang.StringUtils; importorg.apache.log4j.Logger; importcom.company.project.model.menu.AccessToken; importcom.company.project.model.menu.Menu; publicclassWeixinUtil{ privatestaticLoggerlog=Logger.getLogger(WeixinUtil.class); publicfinalstaticStringAPPID="wxb927d4280e6db674"; publicfinalstaticStringAPP_SECRET="21441e9f3226eee81e14380a768b6d1e"; //获取access_token的接口地址(GET)限200(次/天) publicfinalstaticStringaccess_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; //创建菜单 publicfinalstaticStringcreate_menu_url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; //存放:1.token,2:获取token的时间,3.过期时间 publicfinalstaticMap<String,Object>accessTokenMap=newHashMap<String,Object>(); /** *发起https请求并获取结果 * *@paramrequestUrl请求地址 *@paramrequestMethod请求方式(GET、POST) *@paramoutputStr提交的数据 *@returnJSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ publicstaticJSONObjecthandleRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){ JSONObjectjsonObject=null; try{ URLurl=newURL(requestUrl); HttpsURLConnectionconn=(HttpsURLConnection)url.openConnection(); SSLContextctx=SSLContext.getInstance("SSL","SunJSSE"); TrustManager[]tm={newMyX509TrustManager()}; ctx.init(null,tm,newSecureRandom()); SSLSocketFactorysf=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)){ OutputStreamout=conn.getOutputStream(); out.write(outputStr.getBytes("utf-8")); out.close(); } InputStreamin=conn.getInputStream(); BufferedReaderbr=newBufferedReader(newInputStreamReader(in,"utf-8")); StringBufferbuffer=newStringBuffer(); Stringline=null; while((line=br.readLine())!=null){ buffer.append(line); } in.close(); conn.disconnect(); jsonObject=JSONObject.fromObject(buffer.toString()); }catch(MalformedURLExceptione){ e.printStackTrace(); log.error("URL错误!"); }catch(IOExceptione){ e.printStackTrace(); }catch(NoSuchAlgorithmExceptione){ e.printStackTrace(); }catch(NoSuchProviderExceptione){ e.printStackTrace(); }catch(KeyManagementExceptione){ e.printStackTrace(); } returnjsonObject; } /** *获取access_token * *@authorqincd *@dateNov6,20149:56:43AM */ publicstaticAccessTokengetAccessToken(Stringappid,StringappSecret){ AccessTokenat=newAccessToken(); //每次获取access_token时,先从accessTokenMap获取,如果过期了就重新从微信获取 //没有过期直接返回 //从微信获取的token的有效期为2个小时 if(!accessTokenMap.isEmpty()){ DategetTokenTime=(Date)accessTokenMap.get("getTokenTime"); Calendarc=Calendar.getInstance(); c.setTime(getTokenTime); c.add(Calendar.HOUR_OF_DAY,2); getTokenTime=c.getTime(); if(getTokenTime.after(newDate())){ log.info("缓存中发现token未过期,直接从缓存中获取access_token"); //token未过期,直接从缓存获取返回 Stringtoken=(String)accessTokenMap.get("token"); Integerexpire=(Integer)accessTokenMap.get("expire"); at.setToken(token); at.setExpiresIn(expire); returnat; } } StringrequestUrl=access_token_url.replace("APPID",appid).replace("APPSECRET",appSecret); JSONObjectobject=handleRequest(requestUrl,"GET",null); Stringaccess_token=object.getString("access_token"); intexpires_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); //每次获取access_token后,存入accessTokenMap //下次获取时,如果没有过期直接从accessTokenMap取。 accessTokenMap.put("getTokenTime",newDate()); accessTokenMap.put("token",access_token); accessTokenMap.put("expire",expires_in); returnat; } /** *创建菜单 * *@authorqincd *@dateNov6,20149:56:36AM */ publicstaticbooleancreateMenu(Menumenu,StringaccessToken){ StringrequestUrl=create_menu_url.replace("ACCESS_TOKEN",accessToken); StringmenuJsonString=JSONObject.fromObject(menu).toString(); JSONObjectjsonObject=handleRequest(requestUrl,"POST",menuJsonString); StringerrorCode=jsonObject.getString("errcode"); if(!"0".equals(errorCode)){ log.error(String.format("菜单创建失败!errorCode:%d,errorMsg:%s",jsonObject.getInt("errcode"),jsonObject.getString("errmsg"))); returnfalse; } log.info("菜单创建成功!"); returntrue; } //上传多媒体文件到微信服务器 publicstaticfinalStringupload_media_url="http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; /** *上传多媒体文件到微信服务器<br> *@seehttp://www.oschina.net/code/snippet_1029535_23824 *@seehttp://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件 * *@authorqincd *@dateNov6,20144:11:22PM */ publicstaticJSONObjectuploadMediaToWX(StringfilePath,Stringtype,StringaccessToken)throwsIOException{ Filefile=newFile(filePath); if(!file.exists()){ log.error("文件不存在!"); returnnull; } Stringurl=upload_media_url.replace("ACCESS_TOKEN",accessToken).replace("TYPE",type); URLurlObj=newURL(url); HttpURLConnectionconn=(HttpURLConnection)urlObj.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection","Keep-Alive"); conn.setRequestProperty("Charset","UTF-8"); //设置边界 StringBOUNDARY="----------"+System.currentTimeMillis(); conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" +BOUNDARY); //请求正文信息 //第一部分: StringBuildersb=newStringBuilder(); sb.append("--");//////////必须多两道线 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"); //获得输出流 OutputStreamout=newDataOutputStream(conn.getOutputStream()); out.write(head); //文件正文部分 DataInputStreamin=newDataInputStream(newFileInputStream(file)); intbytes=0; byte[]bufferOut=newbyte[1024]; while((bytes=in.read(bufferOut))!=-1){ out.write(bufferOut,0,bytes); } in.close(); //结尾部分 byte[]foot=("\r\n--"+BOUNDARY+"--\r\n").getBytes("utf-8");//定义最后数据分隔线 out.write(foot); out.flush(); out.close(); /** *读取服务器响应,必须读取,否则提交不成功 */ try{ //定义BufferedReader输入流来读取URL的响应 StringBufferbuffer=newStringBuffer(); BufferedReaderreader=newBufferedReader(newInputStreamReader( conn.getInputStream())); Stringline=null; while((line=reader.readLine())!=null){ buffer.append(line); } reader.close(); conn.disconnect(); returnJSONObject.fromObject(buffer.toString()); }catch(Exceptione){ log.error("发送POST请求出现异常!"+e); e.printStackTrace(); } returnnull; } publicstaticfinalStringdownload_media_url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; /** *从微信服务器下载多媒体文件 * *@authorqincd *@dateNov6,20144:32:12PM */ publicstaticStringdownloadMediaFromWx(StringaccessToken,StringmediaId,StringfileSavePath)throwsIOException{ if(StringUtils.isEmpty(accessToken)||StringUtils.isEmpty(mediaId))returnnull; StringrequestUrl=download_media_url.replace("ACCESS_TOKEN",accessToken).replace("MEDIA_ID",mediaId); URLurl=newURL(requestUrl); HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); InputStreamin=conn.getInputStream(); Filedir=newFile(fileSavePath); if(!dir.exists()){ dir.mkdirs(); } if(!fileSavePath.endsWith("/")){ fileSavePath+="/"; } StringContentDisposition=conn.getHeaderField("Content-disposition"); StringweixinServerFileName=ContentDisposition.substring(ContentDisposition.indexOf("filename")+10,ContentDisposition.length()-1); fileSavePath+=weixinServerFileName; BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(fileSavePath)); byte[]data=newbyte[1024]; intlen=-1; while((len=in.read(data))!=-1){ bos.write(data,0,len); } bos.close(); in.close(); conn.disconnect(); returnfileSavePath; } }
测试代码:
publicclassWeixinUtilTest{ /** * *@authorqincd *@dateNov6,20149:57:54AM */ publicstaticvoidmain(String[]args){ //1).获取access_token AccessTokenaccessToken=WeixinUtil.getAccessToken(WeixinUtil.APPID,WeixinUtil.APP_SECRET); StringfilePath="C:\\Users\\qince\\Pictures\\壁纸20141029091612.jpg"; JSONObjectuploadJsonObj=testUploadMedia(filePath,"image",accessToken.getToken()); if(uploadJsonObj==null){ System.out.println("上传图片失败"); return; } interrcode=0; if(uploadJsonObj.containsKey("errcode")){ errcode=uploadJsonObj.getInt("errcode"); } if(errcode==0){ System.out.println("图片上传成功"); StringmediaId=uploadJsonObj.getString("media_id"); longcreateAt=uploadJsonObj.getLong("created_at"); System.out.println("--Details:"); System.out.println("media_id:"+mediaId); System.out.println("created_at:"+createAt); } else{ System.out.println("图片上传失败!"); Stringerrmsg=uploadJsonObj.getString("errmsg"); System.out.println("--Details:"); System.out.println("errcode:"+errcode); System.out.println("errmsg:"+errmsg); } StringmediaId="6W-UvSrQ2hkdSdVQJJXShwtFDPLfbGI1qnbNFy8weZyb9Jac2xxxcAUwt8p4sYPH"; Stringfilepath=testDownloadMedia(accessToken.getToken(),mediaId,"d:/test"); System.out.println(filepath); } /** *上传多媒体文件到微信 * *@authorqincd *@dateNov6,20144:15:14PM */ publicstaticJSONObjecttestUploadMedia(StringfilePath,Stringtype,StringaccessToken){ try{ returnWeixinUtil.uploadMediaToWX(filePath,type,accessToken); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } /** *从微信下载多媒体文件 * *@authorqincd *@dateNov6,20144:56:25PM */ publicstaticStringtestDownloadMedia(StringaccessToken,StringmediaId,StringfileSaveDir){ try{ returnWeixinUtil.downloadMediaFromWx(accessToken,mediaId,fileSaveDir); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } }
更多精彩内容请点击《Android微信开发教程汇总》,《java微信开发教程汇总》欢迎大家学习阅读。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。