欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java微信开发之上传下载多媒体文件

程序员文章站 2024-04-02 15:01:34
回复图片、音频、视频消息都是需要media_id的,这个是需要将多媒体文件上传到微信服务器才有的。 将多媒体文件上传到微信服务器,以及从微信服务器下载文件,可以参考:=上...

回复图片、音频、视频消息都是需要media_id的,这个是需要将多媒体文件上传到微信服务器才有的。

将多媒体文件上传到微信服务器,以及从微信服务器下载文件,可以参考:=上传下载多媒体文件

上传下载多媒体文件的方法还是写到weixinutil.java中。

代码如下:

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";
 // 获取access_token的接口地址(get) 限200(次/天)
 public final static string access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=appsecret";
 // 创建菜单
 public final static string create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=access_token";
 // 存放:1.token,2:获取token的时间,3.过期时间
 public final static map<string,object> accesstokenmap = new hashmap<string,object>();
 /**
 * 发起https请求并获取结果
 * 
 * @param requesturl 请求地址
 * @param requestmethod 请求方式(get、post)
 * @param outputstr 提交的数据
 * @return jsonobject(通过jsonobject.get(key)的方式获取json对象的属性值)
 */
 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错误!");
 } catch (ioexception e) {
 e.printstacktrace();
 } catch (nosuchalgorithmexception e) {
 e.printstacktrace();
 } catch (nosuchproviderexception e) {
 e.printstacktrace();
 } catch (keymanagementexception e) {
 e.printstacktrace();
 }
 return jsonobject;
 }
 
 /**
 * 获取access_token
 *
 * @author qincd
 * @date nov 6, 2014 9:56:43 am
 */
 public static accesstoken getaccesstoken(string appid,string appsecret) {
 accesstoken at = new accesstoken();
 // 每次获取access_token时,先从accesstokenmap获取,如果过期了就重新从微信获取
 // 没有过期直接返回
 // 从微信获取的token的有效期为2个小时
 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未过期,直接从缓存中获取access_token");
 // token未过期,直接从缓存获取返回
 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);
 
 // 每次获取access_token后,存入accesstokenmap
 // 下次获取时,如果没有过期直接从accesstokenmap取。
 accesstokenmap.put("gettokentime", new date());
 accesstokenmap.put("token", access_token);
 accesstokenmap.put("expire", expires_in);
 
 return at;
 }
 
 /**
 * 创建菜单
 *
 * @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("菜单创建失败!errorcode:%d,errormsg:%s",jsonobject.getint("errcode"),jsonobject.getstring("errmsg")));
 return false;
 }
 
 log.info("菜单创建成功!");
 
 return true;
 }
 
 // 上传多媒体文件到微信服务器
 public static final string upload_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=access_token&type=type";
 /**
 * 上传多媒体文件到微信服务器<br>
 * @see http://www.oschina.net/code/snippet_1029535_23824
 * @see http://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件
 *
 * @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("文件不存在!");
 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");
 
  // 设置边界
  string boundary = "----------" + system.currenttimemillis();
  conn.setrequestproperty("content-type", "multipart/form-data; boundary="
    + boundary);
 
  // 请求正文信息
 
  // 第一部分:
  stringbuilder sb = new stringbuilder();
  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");
 
  // 获得输出流
  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();
 
  // 结尾部分
  byte[] foot = ("\r\n--" + boundary + "--\r\n").getbytes("utf-8");// 定义最后数据分隔线
 
  out.write(foot);
 
  out.flush();
  out.close();
 
  /**
   * 读取服务器响应,必须读取,否则提交不成功
   */
   try {
   // 定义bufferedreader输入流来读取url的响应
   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("发送post请求出现异常!" + 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";
 /**
 * 从微信服务器下载多媒体文件
 *
 * @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;
 }
}

测试代码:

public class weixinutiltest {

 /**
 *
 * @author qincd
 * @date nov 6, 2014 9:57:54 am
 */
 public static void main(string[] args) {
 // 1).获取access_token
 accesstoken accesstoken = weixinutil.getaccesstoken(weixinutil.appid, weixinutil.app_secret);
 string filepath = "c:\\users\\qince\\pictures\\壁纸20141029091612.jpg";
 jsonobject uploadjsonobj = testuploadmedia(filepath,"image",accesstoken.gettoken());
 if (uploadjsonobj == null) {
 system.out.println("上传图片失败");
 return;
 }
 
 int errcode = 0;
 if (uploadjsonobj.containskey("errcode")) {
 errcode = uploadjsonobj.getint("errcode");
 }
 if (errcode == 0) {
 system.out.println("图片上传成功");
 
 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("图片上传失败!");
 
 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);
 }


 /**
 * 上传多媒体文件到微信
 *
 * @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;
 }
 
 /**
 * 从微信下载多媒体文件
 *
 * @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;
 }
}

更多精彩内容请点击《android微信开发教程汇总》,《java微信开发教程汇总》欢迎大家学习阅读。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。