多媒体文件上传与下载

第一步:找到包com.wtz.vo,新建类WeixinMedia.java

 package com.wtz.vo;

 /**
* @author wangtianze QQ:864620012
* @date 2017年4月25日 上午11:10:31
* <p>version:1.0</p>
* <p>description:媒体文件信息</p>
*/
public class WeixinMedia {
// 媒体文件类型
private String type;
// 媒体文件标识或缩略图的媒体文件标识
private String mediaId;
// 媒体文件上传的时间
private int createdAt; public String getType() {
return type;
} public void setType(String type) {
this.type = type;
} public String getMediaId() {
return mediaId;
} public void setMediaId(String mediaId) {
this.mediaId = mediaId;
} public int getCreatedAt() {
return createdAt;
} public void setCreatedAt(int createdAt) {
this.createdAt = createdAt;
}
}

第二步,找到包com.wtz.util,修改类AdvancedUtil.java

 package com.wtz.util;

 import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.wtz.vo.UserInfo;
import com.wtz.vo.UserList;
import com.wtz.vo.WeixinMedia; /**
* @author wangtianze QQ:864620012
* @date 2017年4月24日 下午7:36:03
* <p>version:1.0</p>
* <p>description:高级接口工具类</p>
*/
public class AdvancedUtil {
private static Logger log = LoggerFactory.getLogger(AdvancedUtil.class); /**
* 获取用户信息
*
* @param accessToken 接口访问凭证
* @param openId 用户凭证
* @return WeixinUserInfo
*/
public static UserInfo getUserInfo(String accessToken,String openId){
UserInfo weixinUserInfo = null;
//拼接请求地址
String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
requestUrl = requestUrl.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId);
//获取用户信息
JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); if(null != jsonObject){
try{
weixinUserInfo = new UserInfo(); //用户的标识
weixinUserInfo.setOpenId(jsonObject.getString("openid")); //关注状态(1是关注,0是未关注),未关注时获取不到其余信息
weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe")); //用户关注时间
weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time")); //昵称
weixinUserInfo.setNickname(jsonObject.getString("nickname")); //用户的性别(1是男性,2是女性,0是未知)
weixinUserInfo.setSex(jsonObject.getInt("sex")); //用户所在的国家
weixinUserInfo.setCountry(jsonObject.getString("country")); //用户所在的省份
weixinUserInfo.setProvince(jsonObject.getString("province")); //用户所在的城市
weixinUserInfo.setCity(jsonObject.getString("city")); //用户的语言,简体中文为zh_CN
weixinUserInfo.setLanguage(jsonObject.getString("language")); //用户头像
weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl")); //uninonid
weixinUserInfo.setUnionid(jsonObject.getString("unionid"));
}catch(Exception e){
if(0 == weixinUserInfo.getSubscribe()){
log.error("用户{}已取消关注",weixinUserInfo.getOpenId());
}else{
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取用户信息失败 errorcode:{} errormsg:{}",errorCode,errorMsg);
}
}
}
return weixinUserInfo;
} /**
* 获取关注者列表
*
* @param accessToken 调用接口凭证
* @param nextOpenId 第一个拉取nextOpenId,不填默认从头开始拉取
* @return WeixinUserList
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public static UserList getUserList(String accessToken,String nextOpenId){
UserList weixinUserList = null;
if(null == nextOpenId){
nextOpenId = "";
}
//拼接请求地址
String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"; requestUrl.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID",nextOpenId); //获取关注者列表
JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); //如果请求成功
if(null != jsonObject){
weixinUserList = new UserList();
weixinUserList.setTotal(jsonObject.getInt("total"));
weixinUserList.setCount(jsonObject.getInt("count"));
weixinUserList.setNextOpenId(jsonObject.getString("next_openid"));
JSONObject dataObject = (JSONObject)jsonObject.get("data");
weixinUserList.setOpenIdList(JSONArray.toList(dataObject.getJSONArray("openid"),List.class));
} return weixinUserList;
} /**
* 上传媒体文件
* @param accessToken 接口访问凭证
* @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
* @param media form-data中媒体文件标识,有filename、filelength、content-type等信息
* @param mediaFileUrl 媒体文件的url
* 上传的媒体文件限制
* 图片(image):1MB,支持JPG格式
* 语音(voice):2MB,播放长度不超过60s,支持AMR格式
* 视频(video):10MB,支持MP4格式
* 普通文件(file):10MB
* */
public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {
WeixinMedia weixinMedia = null;
// 拼装请求地址
String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type); // 定义数据分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream(); URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET"); // 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileExt = WeixinUtil.getFileExt(contentType);
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes()); // 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect(); // 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
uploadConn.disconnect(); // 使用JSON-lib解析返回结果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
// 测试打印结果
System.out.println("打印测试结果"+jsonObject);
weixinMedia = new WeixinMedia();
weixinMedia.setType(jsonObject.getString("type"));
// type等于 缩略图(thumb) 时的返回结果和其它类型不一样
if ("thumb".equals(type))
weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
else
weixinMedia.setMediaId(jsonObject.getString("media_id"));
weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));
} catch (Exception e) {
weixinMedia = null;
String error = String.format("上传媒体文件失败:%s", e);
System.out.println(error);
}
return weixinMedia;
} /**
* 获取媒体文件
* @param accessToken 接口访问凭证
* @param media_id 媒体文件id
* @param savePath 文件在服务器上的存储路径
* */
public static String downloadMedia(String accessToken, String mediaId, String savePath) {
String filePath = null;
// 拼接请求地址
String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
System.out.println(requestUrl);
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET"); if (!savePath.endsWith("/")) {
savePath += "/";
}
// 根据内容类型获取扩展名
String fileExt = WeixinUtil.getFileExt(conn.getHeaderField("Content-Type"));
// 将mediaId作为文件名
filePath = savePath + mediaId + fileExt; BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(new File(filePath));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close(); conn.disconnect();
String info = String.format("下载媒体文件成功,filePath=" + filePath);
System.out.println(info);
} catch (Exception e) {
filePath = null;
String error = String.format("下载媒体文件失败:%s", e);
System.out.println(error);
}
return filePath;
} public static void main(String[] args){
//获取接口访问凭证
String accessToken = WeixinUtil.getToken(Parameter.appId,Parameter.appSecret).getAccessToken();
System.out.println("accessToken:" + accessToken); //获取关注者列表
UserList weixinUserList = getUserList(accessToken,"");
System.out.println("总关注用户数:" + weixinUserList.getTotal());
System.out.println("本次获取用户数:" + weixinUserList.getCount());
System.out.println("OpenId列表:" + weixinUserList.getOpenIdList().toString());
System.out.println("next_openid" + weixinUserList.getNextOpenId()); UserInfo user = null;
List<String> list = weixinUserList.getOpenIdList();
for(int i = 0; i < list.size(); i++){
//获取用户信息
user = getUserInfo(accessToken,(String)list.get(i));
System.out.println("OpenId:" + user.getOpenId());
System.out.println("关注状态:" + user.getSubscribe());
System.out.println("关注时间:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm-ss").format(new Date(new Long(user.getSubscribeTime())))));
System.out.println("昵称:" + user.getNickname());
System.out.println("性别:" + user.getSex());
System.out.println("国家:" + user.getCountry());
System.out.println("省份:" + user.getProvince());
System.out.println("城市:" + user.getCity());
System.out.println("语言:" + user.getLanguage());
System.out.println("头像:" + user.getHeadImgUrl());
System.out.println("unionid:" + user.getUnionid());
System.out.println("=====================================");
} /**
* 上传多媒体文件
*/
//地址
WeixinMedia weixinMedia = uploadMedia(accessToken, "image", "http://localhost:8080/weixinClient/images/a.jpg");
//media_id
System.out.println("media_id:"+weixinMedia.getMediaId());
//类型
System.out.println("类型:"+weixinMedia.getType());
//时间戳
System.out.println("时间戳:"+weixinMedia.getCreatedAt());
//打印结果
if(null != weixinMedia){
System.out.println("上传成功!");
} /**
* 下载多媒体文件
*/
String savePath = downloadMedia(accessToken, weixinMedia.getMediaId(), "C:/download");
System.out.println("下载成功之后保存在本地的地址为:"+savePath);
}
}

多媒体文件上传与下载完成

Java微信二次开发(九)的更多相关文章

  1. Java微信二次开发(一)

    准备用Java做一个微信二次开发项目,把流程写在这里吧. 第一天,做微信请求验证 需要导入库:servlet-api.jar 第一步:新建包com.wtz.service,新建类LoginServle ...

  2. Java微信二次开发(五)

    消息加密 需要到入库:commons-io-2.4.jar,commons-codec-1.9.jar(在官网的Java微信加密demo下) 第一步:访问https://mp.weixin.qq.co ...

  3. Java微信公众平台开发(九)--关键字回复以及客服接口实现(该公众号暂时无法提供服务解决方案)

    转自:http://www.cuiyongzhi.com/post/47.html 我们在微信公众号的后台可以发现微信给我们制定了两种模式,一种是开发者模式(也就是我们一直在做的开发),还有一种模式是 ...

  4. Java微信公众平台开发(九)--微信自定义菜单的创建实现

    自定义菜单这个功能在我们普通的编辑模式下是可以直接在后台编辑的,但是一旦我们进入开发模式之后我们的自定义菜单就需要自己用代码实现,所以对于刚开始接触的人来说可能存在一定的疑惑,这里我说下平时我们在开发 ...

  5. Java微信二次开发(十)

    生成带参数的二维码以及长链接转短链接 第一步:找到包com.wtz.vo,新建类WeixinQRCode.java package com.wtz.vo; /** * @author wangtian ...

  6. Java微信二次开发(七)

    自定义菜单 第一步:新建包com.wtz.menu,新建类Button.java package com.wtz.menu; /** * @author wangtianze QQ:864620012 ...

  7. Java微信二次开发(三)

    各种类型消息的封装 第一步:找到com.wtz.message.response包,新建类Image.java package com.wtz.message.response; /** * @aut ...

  8. Java微信二次开发(八)

    高级接口,先做了两个(获取用户信息和获取关注者列表) 第一步:找到包com.wtz.vo,新建类UserInfo.java package com.wtz.vo; /** * @author wang ...

  9. Java微信二次开发(六)

    Token定时获取 需要导入库:添加log4j(slf4j-api-1.5.10.jar,slf4j-log4j12-1.5.10.jar,log4j-1.2.15.jar,并且在src下添加log4 ...

随机推荐

  1. PAT A1130 Infix Expression (25 分)——中序遍历

    Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with pa ...

  2. [06] Bean属性的注入

    之前我们提到了Bean实例化的三种方式:构造器方式.静态工厂方式.普通工厂方式.那么对于Bean中的属性,又是如何进行注入的(依赖注入),这个篇章就来提一提. 1.先提提什么是"依赖注入&q ...

  3. VS诊断工具打开失败

    使用管理员模式打开cmd,输入以下命令~ C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -iC:\Windows\Micros ...

  4. SSIS ->> Excel Destination无法接受大于255个字符长度的字符字段(转载)

    从下文的链接中找到一些背景,因为Excel会以前8行作为参考,如果某个字段前8行的最长长度没有超过255个字符,就会报错.如果知道某个字段属于描述性字段,而且字段的数据长度很可能超过255个字符长度, ...

  5. Hive 数据的导入导出

    数据的导入: 通过文件导入,使用load命令 一.导入本地文件: load data local inpath '/home/hadoop/files/emp.txt' overwrite into ...

  6. java,javascript中的url编码

    真实场景 url示例如下 http://localhost:31956/Login/Auto?Token=e8a67a9f-c062-4964-b703-d79f29c8b64e&Return ...

  7. 51Nod 1443 路径和树

    还是一道很简单的基础题,就是一个最短路径树的类型题目 我们首先可以发现这棵树必定满足从1出发到其它点的距离都是原图中的最短路 换句话说,这棵树上的每一条边都是原图从1出发到其它点的最短路上的边 那么直 ...

  8. 事务,acid,cap,paxos随笔

    事务ACID四个特性: A:原子性(Atomicity)C:一致性(Consistency)I:隔离性(Isolation)D:持久性(Durability) 原子性:语句要么全执行,要么全不执行,是 ...

  9. Zabbix监控系统部署:配置详解

    1. 全局配置 ListenPort ,监听端口 ,取值范围为1024-32767,默认端口10051 SourceIP,外发连接源地址 LogType,日志类型:单独日志文件,系统文件,控制台输出 ...

  10. Object-Oriented(一)创建对象

    自用备忘笔记 前言 虽然可以使用 Object 和对象字面量创建对象,但是如果要创建大量相似的对象又显得麻烦.为解决这个问题,人们开始使用工厂模式的变种. 工厂模式 function person(n ...