微信公众平台开发中的结合BAE进行IO操作的一些要点进行整理,主要是为了实现图文消息的上传,和用模拟登陆的方式下载客户发送给公众账号的语音消息、图片消息等。
package com.weinxin.utils; import com.baidu.inf.iis.bcs.BaiduBCS; import com.baidu.inf.iis.bcs.auth.BCSCredentials; public class BaiduBCSTools { public static String ACCESSKEY = "F0909c0717a319bb6e2**********"; public static String SECRETKEY = "84c09d2f43873b15c310**********"; public static String IMAGE_BUCKET = "myimage";// 图片容器 public static String VOICE_BUCKET = "hwnvoice";// 音频容器 public static String OTHER_BUCKET = "otherfile";// 其他类型的容器 public static String HOST = "bcs.duapp.com"; // 目录 public static String IMAGE_FOLDER = "/image/"; public static String VOICE_FOLDER = "/voice/"; public static String OTHER_FOLDER = "/other/"; /** * * 功能说明: 获取BaiduBCS对象 * @return BaiduBCS对象 */ public static BaiduBCS getBaiduBCS(){ BCSCredentials credentials = new BCSCredentials(ACCESSKEY, SECRETKEY); BaiduBCS baiduBCS = new BaiduBCS(credentials, HOST); baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8 return baiduBCS; } }
基于此编写的,通过模拟登陆的方式获取微信附件的工具代码如下:
package com.weixin.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import com.baidu.inf.iis.bcs.BaiduBCS; import com.baidu.inf.iis.bcs.model.ObjectMetadata; import com.baidu.inf.iis.bcs.request.PutObjectRequest; import com.baidu.inf.iis.bcs.response.BaiduBCSResponse; import com.weixin.modules.model.Message; import com.weixin.utils.MD5; public class DownLoadUtils { public static final String LOGIN_URL = "http://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN"; public static String DOWNLOAD_URL = "https://mp.weixin.qq.com/cgi-bin/downloadfile?msgid=#msgId&token="; public static final String USERNAME = "******@163.com"; public static final String PASSWORD = "********"; /** * * 功能说明: 获取登陆微信公众平台后的cookie * @return cookie字符串 * @throws Exception */ public static String getCookies() throws Exception { URL url = new URL(LOGIN_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true);// 允许连接提交信息 connection.setRequestMethod("POST");// 网页提交方式“GET”、“POST” connection.setRequestProperty("User-Agent", "Mozilla/4.7 [en] (Win98; I)"); StringBuffer sb = new StringBuffer(); sb.append("username=" + USERNAME); sb.append("&pwd=" + MD5.getMD5(PASSWORD.getBytes()) .toUpperCase()); OutputStream os = connection.getOutputStream(); os.write(sb.toString().getBytes()); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader( connection.getInputStream())); String cookieVal = null; String response_cookie = ""; String key=null; for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++ ) { if (key.equalsIgnoreCase("Set-Cookie")) { cookieVal = connection.getHeaderField(i); cookieVal = cookieVal.substring(0, cookieVal.indexOf(";")); response_cookie = response_cookie + cookieVal + ";"; } } System.out.println("response_cookie==" + response_cookie); String line = br.readLine(); while (line != null) { // 获取token if(line.contains("ErrMsg")){ DOWNLOAD_URL += line.substring(line.lastIndexOf("=") + 1, line.lastIndexOf("\"")); } line = br.readLine();// 打出登录的网页 } return response_cookie; } /** * * 功能说明: 下载指定消息ID的文件并保存到百度空间 * @param msgId 消息ID * @param message 消息体 * @param fileType 文件类型 * @return 消息保存到百度空间后的名字 * @throws Exception */ public static String download(String msgId, Message message, String fileType) throws Exception{ String cookies = getCookies(); String file_name = null; if("voice".equalsIgnoreCase(fileType)){ file_name = BaiduBCSTools.VOICE_FOLDER + msgId; }else if("image".equalsIgnoreCase(fileType)){ file_name = BaiduBCSTools.IMAGE_FOLDER + msgId; }else { file_name = BaiduBCSTools.OTHER_FOLDER + msgId; } String url = DOWNLOAD_URL.replace("#msgId", msgId); URL download_url = new URL(url); HttpURLConnection download_conn = (HttpURLConnection) download_url .openConnection(); download_conn.setRequestProperty("Cookie", cookies);// 设置服务器送登录后的cookie ObjectMetadata metadata = new ObjectMetadata(); String type = download_conn.getContentType(); // 后缀名称 String suffix = type.substring(type.lastIndexOf("/") + 1); file_name += "." + suffix; System.out.println("type=" + type + ",suffix=" + suffix); long length = download_conn.getContentLength(); if(message != null){ // message.setFileLength(length + ""); } metadata.setContentType(type); metadata.setContentLength(length); PutObjectRequest request = null; try { InputStream in = download_conn.getInputStream(); BaiduBCS baiduBCS = BaiduBCSTools.getBaiduBCS(); String bucket = null; if("voice".equalsIgnoreCase(fileType)){ bucket = BaiduBCSTools.VOICE_BUCKET; }else if("image".equalsIgnoreCase(fileType)){ bucket = BaiduBCSTools.IMAGE_BUCKET; }else { bucket = BaiduBCSTools.OTHER_BUCKET; } request = new PutObjectRequest(bucket, file_name, in, metadata); BaiduBCSResponse<ObjectMetadata> response = baiduBCS.putObject(request); ObjectMetadata objectMetadata = response.getResult(); System.out.println("objectMetadata="+objectMetadata+",request-id="+response.getRequestId()); } catch (IOException e) { e.printStackTrace(); } return file_name; } public static void main(String[] args) { String msgId = "5885899705870713317"; try { String file_name = download(msgId, null, "image"); System.out.println("file_name==" + file_name); } catch (Exception e) { e.printStackTrace(); } } }