Java微信二次开发(九)
多媒体文件上传与下载
第一步:找到包com.wtz.vo,新建类WeixinMedia.java
1 package com.wtz.vo; 2 3 /** 4 * @author wangtianze QQ:864620012 5 * @date 2017年4月25日 上午11:10:31 6 * <p>version:1.0</p> 7 * <p>description:媒体文件信息</p> 8 */ 9 public class WeixinMedia { 10 // 媒体文件类型 11 private String type; 12 // 媒体文件标识或缩略图的媒体文件标识 13 private String mediaId; 14 // 媒体文件上传的时间 15 private int createdAt; 16 17 public String getType() { 18 return type; 19 } 20 21 public void setType(String type) { 22 this.type = type; 23 } 24 25 public String getMediaId() { 26 return mediaId; 27 } 28 29 public void setMediaId(String mediaId) { 30 this.mediaId = mediaId; 31 } 32 33 public int getCreatedAt() { 34 return createdAt; 35 } 36 37 public void setCreatedAt(int createdAt) { 38 this.createdAt = createdAt; 39 } 40 }
第二步,找到包com.wtz.util,修改类AdvancedUtil.java
1 package com.wtz.util; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedReader; 5 import java.io.File; 6 import java.io.FileOutputStream; 7 import java.io.InputStream; 8 import java.io.InputStreamReader; 9 import java.io.OutputStream; 10 import java.net.HttpURLConnection; 11 import java.net.URL; 12 import java.text.SimpleDateFormat; 13 import java.util.Date; 14 import java.util.List; 15 16 import net.sf.json.JSONArray; 17 import net.sf.json.JSONObject; 18 19 import org.slf4j.Logger; 20 import org.slf4j.LoggerFactory; 21 22 import com.wtz.vo.UserInfo; 23 import com.wtz.vo.UserList; 24 import com.wtz.vo.WeixinMedia; 25 26 /** 27 * @author wangtianze QQ:864620012 28 * @date 2017年4月24日 下午7:36:03 29 * <p>version:1.0</p> 30 * <p>description:高级接口工具类</p> 31 */ 32 public class AdvancedUtil { 33 private static Logger log = LoggerFactory.getLogger(AdvancedUtil.class); 34 35 /** 36 * 获取用户信息 37 * 38 * @param accessToken 接口访问凭证 39 * @param openId 用户凭证 40 * @return WeixinUserInfo 41 */ 42 public static UserInfo getUserInfo(String accessToken,String openId){ 43 UserInfo weixinUserInfo = null; 44 //拼接请求地址 45 String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID"; 46 requestUrl = requestUrl.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId); 47 //获取用户信息 48 JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); 49 50 if(null != jsonObject){ 51 try{ 52 weixinUserInfo = new UserInfo(); 53 54 //用户的标识 55 weixinUserInfo.setOpenId(jsonObject.getString("openid")); 56 57 //关注状态(1是关注,0是未关注),未关注时获取不到其余信息 58 weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe")); 59 60 //用户关注时间 61 weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time")); 62 63 //昵称 64 weixinUserInfo.setNickname(jsonObject.getString("nickname")); 65 66 //用户的性别(1是男性,2是女性,0是未知) 67 weixinUserInfo.setSex(jsonObject.getInt("sex")); 68 69 //用户所在的国家 70 weixinUserInfo.setCountry(jsonObject.getString("country")); 71 72 //用户所在的省份 73 weixinUserInfo.setProvince(jsonObject.getString("province")); 74 75 //用户所在的城市 76 weixinUserInfo.setCity(jsonObject.getString("city")); 77 78 //用户的语言,简体中文为zh_CN 79 weixinUserInfo.setLanguage(jsonObject.getString("language")); 80 81 //用户头像 82 weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl")); 83 84 //uninonid 85 weixinUserInfo.setUnionid(jsonObject.getString("unionid")); 86 }catch(Exception e){ 87 if(0 == weixinUserInfo.getSubscribe()){ 88 log.error("用户{}已取消关注",weixinUserInfo.getOpenId()); 89 }else{ 90 int errorCode = jsonObject.getInt("errcode"); 91 String errorMsg = jsonObject.getString("errmsg"); 92 log.error("获取用户信息失败 errorcode:{} errormsg:{}",errorCode,errorMsg); 93 } 94 } 95 } 96 return weixinUserInfo; 97 } 98 99 /** 100 * 获取关注者列表 101 * 102 * @param accessToken 调用接口凭证 103 * @param nextOpenId 第一个拉取nextOpenId,不填默认从头开始拉取 104 * @return WeixinUserList 105 */ 106 @SuppressWarnings({ "deprecation", "unchecked" }) 107 public static UserList getUserList(String accessToken,String nextOpenId){ 108 UserList weixinUserList = null; 109 if(null == nextOpenId){ 110 nextOpenId = ""; 111 } 112 //拼接请求地址 113 String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"; 114 115 requestUrl.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID",nextOpenId); 116 117 //获取关注者列表 118 JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); 119 120 //如果请求成功 121 if(null != jsonObject){ 122 weixinUserList = new UserList(); 123 weixinUserList.setTotal(jsonObject.getInt("total")); 124 weixinUserList.setCount(jsonObject.getInt("count")); 125 weixinUserList.setNextOpenId(jsonObject.getString("next_openid")); 126 JSONObject dataObject = (JSONObject)jsonObject.get("data"); 127 weixinUserList.setOpenIdList(JSONArray.toList(dataObject.getJSONArray("openid"),List.class)); 128 } 129 130 return weixinUserList; 131 } 132 133 /** 134 * 上传媒体文件 135 * @param accessToken 接口访问凭证 136 * @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file) 137 * @param media form-data中媒体文件标识,有filename、filelength、content-type等信息 138 * @param mediaFileUrl 媒体文件的url 139 * 上传的媒体文件限制 140 * 图片(image):1MB,支持JPG格式 141 * 语音(voice):2MB,播放长度不超过60s,支持AMR格式 142 * 视频(video):10MB,支持MP4格式 143 * 普通文件(file):10MB 144 * */ 145 public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) { 146 WeixinMedia weixinMedia = null; 147 // 拼装请求地址 148 String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; 149 uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type); 150 151 // 定义数据分隔符 152 String boundary = "------------7da2e536604c8"; 153 try { 154 URL uploadUrl = new URL(uploadMediaUrl); 155 HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection(); 156 uploadConn.setDoOutput(true); 157 uploadConn.setDoInput(true); 158 uploadConn.setRequestMethod("POST"); 159 // 设置请求头Content-Type 160 uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 161 // 获取媒体文件上传的输出流(往微信服务器写数据) 162 OutputStream outputStream = uploadConn.getOutputStream(); 163 164 URL mediaUrl = new URL(mediaFileUrl); 165 HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection(); 166 meidaConn.setDoOutput(true); 167 meidaConn.setRequestMethod("GET"); 168 169 // 从请求头中获取内容类型 170 String contentType = meidaConn.getHeaderField("Content-Type"); 171 // 根据内容类型判断文件扩展名 172 String fileExt = WeixinUtil.getFileExt(contentType); 173 // 请求体开始 174 outputStream.write(("--" + boundary + "\r\n").getBytes()); 175 outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes()); 176 outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes()); 177 178 // 获取媒体文件的输入流(读取文件) 179 BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream()); 180 byte[] buf = new byte[8096]; 181 int size = 0; 182 while ((size = bis.read(buf)) != -1) { 183 // 将媒体文件写到输出流(往微信服务器写数据) 184 outputStream.write(buf, 0, size); 185 } 186 // 请求体结束 187 outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes()); 188 outputStream.close(); 189 bis.close(); 190 meidaConn.disconnect(); 191 192 // 获取媒体文件上传的输入流(从微信服务器读数据) 193 InputStream inputStream = uploadConn.getInputStream(); 194 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 195 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 196 StringBuffer buffer = new StringBuffer(); 197 String str = null; 198 while ((str = bufferedReader.readLine()) != null) { 199 buffer.append(str); 200 } 201 bufferedReader.close(); 202 inputStreamReader.close(); 203 // 释放资源 204 inputStream.close(); 205 inputStream = null; 206 uploadConn.disconnect(); 207 208 // 使用JSON-lib解析返回结果 209 JSONObject jsonObject = JSONObject.fromObject(buffer.toString()); 210 // 测试打印结果 211 System.out.println("打印测试结果"+jsonObject); 212 weixinMedia = new WeixinMedia(); 213 weixinMedia.setType(jsonObject.getString("type")); 214 // type等于 缩略图(thumb) 时的返回结果和其它类型不一样 215 if ("thumb".equals(type)) 216 weixinMedia.setMediaId(jsonObject.getString("thumb_media_id")); 217 else 218 weixinMedia.setMediaId(jsonObject.getString("media_id")); 219 weixinMedia.setCreatedAt(jsonObject.getInt("created_at")); 220 } catch (Exception e) { 221 weixinMedia = null; 222 String error = String.format("上传媒体文件失败:%s", e); 223 System.out.println(error); 224 } 225 return weixinMedia; 226 } 227 228 /** 229 * 获取媒体文件 230 * @param accessToken 接口访问凭证 231 * @param media_id 媒体文件id 232 * @param savePath 文件在服务器上的存储路径 233 * */ 234 public static String downloadMedia(String accessToken, String mediaId, String savePath) { 235 String filePath = null; 236 // 拼接请求地址 237 String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; 238 requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId); 239 System.out.println(requestUrl); 240 try { 241 URL url = new URL(requestUrl); 242 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 243 conn.setDoInput(true); 244 conn.setRequestMethod("GET"); 245 246 if (!savePath.endsWith("/")) { 247 savePath += "/"; 248 } 249 // 根据内容类型获取扩展名 250 String fileExt = WeixinUtil.getFileExt(conn.getHeaderField("Content-Type")); 251 // 将mediaId作为文件名 252 filePath = savePath + mediaId + fileExt; 253 254 BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 255 FileOutputStream fos = new FileOutputStream(new File(filePath)); 256 byte[] buf = new byte[8096]; 257 int size = 0; 258 while ((size = bis.read(buf)) != -1) 259 fos.write(buf, 0, size); 260 fos.close(); 261 bis.close(); 262 263 conn.disconnect(); 264 String info = String.format("下载媒体文件成功,filePath=" + filePath); 265 System.out.println(info); 266 } catch (Exception e) { 267 filePath = null; 268 String error = String.format("下载媒体文件失败:%s", e); 269 System.out.println(error); 270 } 271 return filePath; 272 } 273 274 public static void main(String[] args){ 275 //获取接口访问凭证 276 String accessToken = WeixinUtil.getToken(Parameter.appId,Parameter.appSecret).getAccessToken(); 277 System.out.println("accessToken:" + accessToken); 278 279 //获取关注者列表 280 UserList weixinUserList = getUserList(accessToken,""); 281 System.out.println("总关注用户数:" + weixinUserList.getTotal()); 282 System.out.println("本次获取用户数:" + weixinUserList.getCount()); 283 System.out.println("OpenId列表:" + weixinUserList.getOpenIdList().toString()); 284 System.out.println("next_openid" + weixinUserList.getNextOpenId()); 285 286 UserInfo user = null; 287 List<String> list = weixinUserList.getOpenIdList(); 288 for(int i = 0; i < list.size(); i++){ 289 //获取用户信息 290 user = getUserInfo(accessToken,(String)list.get(i)); 291 System.out.println("OpenId:" + user.getOpenId()); 292 System.out.println("关注状态:" + user.getSubscribe()); 293 System.out.println("关注时间:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm-ss").format(new Date(new Long(user.getSubscribeTime()))))); 294 System.out.println("昵称:" + user.getNickname()); 295 System.out.println("性别:" + user.getSex()); 296 System.out.println("国家:" + user.getCountry()); 297 System.out.println("省份:" + user.getProvince()); 298 System.out.println("城市:" + user.getCity()); 299 System.out.println("语言:" + user.getLanguage()); 300 System.out.println("头像:" + user.getHeadImgUrl()); 301 System.out.println("unionid:" + user.getUnionid()); 302 System.out.println("====================================="); 303 } 304 305 /** 306 * 上传多媒体文件 307 */ 308 //地址 309 WeixinMedia weixinMedia = uploadMedia(accessToken, "image", "http://localhost:8080/weixinClient/images/a.jpg"); 310 //media_id 311 System.out.println("media_id:"+weixinMedia.getMediaId()); 312 //类型 313 System.out.println("类型:"+weixinMedia.getType()); 314 //时间戳 315 System.out.println("时间戳:"+weixinMedia.getCreatedAt()); 316 //打印结果 317 if(null != weixinMedia){ 318 System.out.println("上传成功!"); 319 } 320 321 /** 322 * 下载多媒体文件 323 */ 324 String savePath = downloadMedia(accessToken, weixinMedia.getMediaId(), "C:/download"); 325 System.out.println("下载成功之后保存在本地的地址为:"+savePath); 326 } 327 }
多媒体文件上传与下载完成
posted on 2017-04-25 13:37 wangtianze 阅读(693) 评论(0) 编辑 收藏 举报