多媒体文件上传与下载

第一步:找到包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. 【Codeforces 113B】Petr#

    Codeforces 113 B 题意:有一个母串\(S\)以及两个串\(S_{begin}\)和\(S_{end}\),问\(S\)中以\(S_{begin}\)为开头并且以\(S_{end}\)为 ...

  2. 即时通讯IM工具

    即时通讯IM工具,目前已知的服务及收费方式:一.专业第三方IMLeanCloud(按需收费)LeanCloud融云(免费+收费)融云即时通讯云环信(免费+收费)环信-即时通讯云领导者云之讯(免费+收费 ...

  3. jdk_1_8_1

    JAVA_HOME=/usr/local/java/jdk1.8.0_181 PATH=$JAVA_HOME/bin:$PATH JAVA_BINDIR=/usr/local/java/jdk1.8. ...

  4. coredns CrashLoopBackOff 报错

    1.kubectl logs -f coredns-99b9bb8bd-47mvf -n kube-system .:53 2018/09/22 07:39:37 [INFO] CoreDNS-1.2 ...

  5. 交换左Ctrl键和Caps lock键

    Windows 10 Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control ...

  6. 【Linux系统目录结构】

    登录系统后,在当前命令窗口下输入 ls / 你会看到 以下是对这些目录的解释: /bin bin是Binary的缩写.这个目录存放着最经常使用的命令. /boot 这里存放的是启动Linux时使用的一 ...

  7. javascript闭包的使用--按钮切换

    闭包实现按钮状态切换 看下面的代码: var toggleBtn = document.getElementById('toggle'); var toggleFun = (function() { ...

  8. CF1056E Check Transcription 字符串哈希

    传送门 暴力枚举\(0\)的长度,如果对应的\(1\)的长度也是一个整数就去check是否合法.check使用字符串哈希. 复杂度看起来是\(O(st)\)的,但是因为\(01\)两个数中数量较多的至 ...

  9. (转)Xpath语法格式整理

    原文 经常在工作中会使用到XPath的相关知识,但每次总会在一些关键的地方不记得或不太清楚,所以免不了每次总要查一些零碎的知识,感觉即很烦又浪费时间,所以对XPath归纳及总结一下. 在这篇文章中你将 ...

  10. C# 队列和栈 线程安全

    队列是其元素以先进先出(FIFO)的方式来处理集合,先入队的元素会先读取. 栈是和队列非常类似的另一个容器,栈和队列最大的区别是后进先出(LIFO),也可以说成先进后出. 队列在现实生活中的例子数不胜 ...