多媒体文件上传与下载
第一步:找到包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);
}
}
多媒体文件上传与下载完成