微信开发之消息回复--图片消息(五)
一、消息格式
1 <xml> 2 <ToUserName> 3 < ![CDATA[toUser] ]> 4 </ToUserName> 5 <FromUserName> 6 < ![CDATA[fromUser] ]> 7 </FromUserName> 8 <CreateTime>12345678</CreateTime> 9 <MsgType> 10 < ![CDATA[image] ]> 11 </MsgType> 12 <Image> 13 <MediaId> 14 < ![CDATA[media_id] ]> 15 </MediaId> 16 </Image> 17 </xml>
二、参数介绍
参数 | 是否必须 | 说明 |
---|---|---|
ToUserName | 是 | 接收方帐号(收到的OpenID) |
FromUserName | 是 | 开发者微信号 |
CreateTime | 是 | 消息创建时间 (整型) |
MsgType | 是 | image |
MediaId | 是 | 通过素材管理中的接口上传多媒体文件,得到的id。 |
三、图片消息实体类
1 public class Image { 2 3 private String MediaId; 4 5 public String getMediaId() { 6 return MediaId; 7 } 8 9 public void setMediaId(String mediaId) { 10 MediaId = mediaId; 11 } 12 13 @Override 14 public String toString() { 15 return "Image [MediaId=" + MediaId + "]"; 16 } 17 18 }
public class ImageMessage extends BaseMessge{ private Image Image;// public Image getImage() { return Image; } public void setImage(Image image) { Image = image; } @Override public String toString() { return "ImageMessage [Image=" + Image + "]"; } }
四、添加将图片消息转换为xml方法
1 /** 2 * 将图片消息转换为xml 3 * @param imageMessage 4 * @return 5 */ 6 public static String imageMessageToXml(ImageMessage imageMessage){ 7 //XStream xStream = new XStream(new StaxDriver()); 8 xStream.alias("xml", imageMessage.getClass()); 9 return xStream.toXML(imageMessage); 10 }
五、添加初始化图片消息代码
1 //初始化图片消息 2 public static String initImageMessage(String toUserName,String fromUserName){ 3 String message=""; 4 //获取access_token 5 String access_token = WeixinUtil.getAccessToken().getToken(); 6 String path = "E:/test.jpg";//需替换图片路径 7 try{ 8 Image image = new Image(); 9 ImageMessage imageMessage = new ImageMessage(); 10 String mediaId = WeixinUtil.upload(path, access_token, "image"); 11 image.setMediaId(mediaId); 12 imageMessage.setFromUserName(toUserName); 13 imageMessage.setToUserName(fromUserName); 14 imageMessage.setMsgType(MsgTypeParam.MESSAGE_IMAGE); 15 imageMessage.setCreateTime(new Date().getTime()+""); 16 imageMessage.setImage(image); 17 message = MessageUtil.imageMessageToXml(imageMessage); 18 System.err.println(message); 19 }catch(Exception e){ 20 e.printStackTrace(); 21 } 22 return message; 23 }
六、修改Servlet中的Post方法,加入如下代码:
if("图片".equals(content)){ //调用初始化图片消息的方法 message = InitMsgContentUtil.initImageMessage(toUserName, fromUserName); }
七、项目部署及查看结果
向公众号发送信息,看是否能够正常返回信息。效果图如下:
以上代码中所用到的其他方法全部如下:
CommUtil 工具类:
1 package com.weixin.util; 2 import java.io.BufferedReader; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStream; 6 import java.io.UnsupportedEncodingException; 7 import java.net.ConnectException; 8 import java.net.URL; 9 import javax.net.ssl.HttpsURLConnection; 10 import javax.net.ssl.SSLContext; 11 import javax.net.ssl.SSLSocketFactory; 12 import javax.net.ssl.TrustManager; 13 import net.sf.json.JSONException; 14 import net.sf.json.JSONObject; 15 import org.apache.http.HttpResponse; 16 import org.apache.http.HttpStatus; 17 import org.apache.http.client.HttpClient; 18 import org.apache.http.client.methods.HttpGet; 19 import org.apache.http.impl.client.DefaultHttpClient; 20 import org.apache.http.util.EntityUtils; 21 import org.slf4j.Logger; 22 import org.slf4j.LoggerFactory; 23 24 import com.weixin.entity.AccessToken; 25 26 public class CommUtil { 27 28 private static Logger log = LoggerFactory.getLogger(CommUtil.class); 29 // 获取access_token的接口地址(GET) 限200(次/天) 30 public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 31 32 /** 33 * 发起https请求并获取结果 34 * @param requestUrl 请求地址 35 * @param requestMethod 请求方式(GET、POST) 36 * @param outputStr 提交的数据 37 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 38 */ 39 public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { 40 JSONObject jsonObject = null; 41 StringBuffer buffer = new StringBuffer(); 42 try { 43 // 创建SSLContext对象,并使用我们指定的信任管理器初始化 44 TrustManager[] tm = { new MyX509TrustManager() }; 45 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); 46 sslContext.init(null, tm, new java.security.SecureRandom()); 47 // 从上述SSLContext对象中得到SSLSocketFactory对象 48 SSLSocketFactory ssf = sslContext.getSocketFactory(); 49 URL url = new URL(requestUrl); 50 HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); 51 httpUrlConn.setSSLSocketFactory(ssf); 52 httpUrlConn.setDoOutput(true); 53 httpUrlConn.setDoInput(true); 54 httpUrlConn.setUseCaches(false); 55 // 设置请求方式(GET/POST) 56 httpUrlConn.setRequestMethod(requestMethod); 57 if ("GET".equalsIgnoreCase(requestMethod)){ 58 httpUrlConn.connect(); 59 } 60 // 当有数据需要提交时 61 if (null != outputStr) { 62 OutputStream outputStream = httpUrlConn.getOutputStream(); 63 // 注意编码格式,防止中文乱码 64 outputStream.write(outputStr.getBytes("UTF-8")); 65 outputStream.close(); 66 } 67 // 将返回的输入流转换成字符串 68 InputStream inputStream = httpUrlConn.getInputStream(); 69 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); 70 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 71 String str = null; 72 while ((str = bufferedReader.readLine()) != null) { 73 buffer.append(str); 74 } 75 bufferedReader.close(); 76 inputStreamReader.close(); 77 // 释放资源 78 inputStream.close(); 79 inputStream = null; 80 httpUrlConn.disconnect(); 81 jsonObject = JSONObject.fromObject(buffer.toString()); 82 } catch (ConnectException ce) { 83 log.error("Weixin server connection timed out."); 84 } catch (Exception e) { 85 log.error("https request error:{}", e); 86 } 87 return jsonObject; 88 } 89 /** 90 * 91 * @Description: 获取access_token 92 * @param appid 93 * @param appsecret 94 * @Title: getAccessToken 95 * @return AccessToken 96 * @date: 2015年9月8日 下午2:23:01 97 * @author heboy 98 */ 99 public static AccessToken getAccessToken(String appid, String appsecret) { 100 AccessToken accessToken = null; 101 String requestUrl = ACCESS_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", appsecret); 102 JSONObject jsonObject = httpRequest(requestUrl, "GET", null); 103 // 如果请求成功 104 if (null != jsonObject) { 105 try { 106 accessToken = new AccessToken(); 107 accessToken.setToken(jsonObject.getString("access_token")); 108 accessToken.setExpiresIn(jsonObject.getInt("expires_in")); 109 } catch (JSONException e) { 110 accessToken = null; 111 // 获取token失败 112 log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); 113 } 114 } 115 return accessToken; 116 } 117 118 /** 119 * URL编码(utf-8) 120 * @param source 121 * @return 122 */ 123 public static String urlEncodeUTF8(String source) { 124 String result = source; 125 try { 126 result = java.net.URLEncoder.encode(source, "utf-8"); 127 } catch (UnsupportedEncodingException e) { 128 e.printStackTrace(); 129 } 130 return result; 131 } 132 /** 133 * 获取URL 134 * @param url 135 * @return 136 */ 137 public static String getUrl(String url){ 138 String result = null; 139 try { 140 // 根据地址获取请求 141 HttpGet request = new HttpGet(url); 142 // 获取当前客户端对象 143 HttpClient httpClient = new DefaultHttpClient(); 144 // 通过请求对象获取响应对象 145 HttpResponse response = httpClient.execute(request); 146 // 判断网络连接状态码是否正常(0--200都数正常) 147 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 148 result= EntityUtils.toString(response.getEntity(),"UTF-8"); 149 } 150 } catch (Exception e) { 151 // TODO Auto-generated catch block 152 e.printStackTrace(); 153 } 154 return result; 155 } 156 }
WeixinUtil工具类:
1 package com.weixin.util; 2 3 import java.io.BufferedReader; 4 import java.io.DataInputStream; 5 import java.io.DataOutputStream; 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.IOException; 9 import java.io.InputStreamReader; 10 import java.io.OutputStream; 11 import java.net.HttpURLConnection; 12 import java.net.URL; 13 import java.security.KeyManagementException; 14 import java.security.NoSuchAlgorithmException; 15 import java.security.NoSuchProviderException; 16 import net.sf.json.JSONObject; 17 import org.apache.http.HttpEntity; 18 import org.apache.http.HttpResponse; 19 import org.apache.http.client.ClientProtocolException; 20 import org.apache.http.client.methods.HttpGet; 21 import org.apache.http.client.methods.HttpPost; 22 import org.apache.http.entity.StringEntity; 23 import org.apache.http.impl.client.DefaultHttpClient; 24 import org.apache.http.util.EntityUtils; 25 import com.weixin.entity.AccessToken; 26 27 public class WeixinUtil { 28 29 public static final String APPID = "替换你的"; 30 public static final String APPSECRET = "替换你的"; 31 //获取acces_token 接口地址 32 public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 33 //上传文件url接口地址 34 private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; 35 36 /** 37 * Get请求 38 * @param url 39 * @return 40 * 注意事项 添加jsonobject的jar包及依赖jar包 41 * 添加httpclient,httpcore的 jar包 42 */ 43 public static JSONObject doGetStr(String url){ 44 DefaultHttpClient httpClient = new DefaultHttpClient(); 45 HttpGet httpGet = new HttpGet(url); 46 JSONObject jsonObject = null; 47 try{ 48 HttpResponse response = httpClient.execute(httpGet); 49 HttpEntity entity = response.getEntity(); 50 if(entity != null){ 51 String result = EntityUtils.toString(entity,"UTF-8"); 52 jsonObject = JSONObject.fromObject(result); 53 } 54 }catch(ClientProtocolException e){ 55 e.printStackTrace(); 56 }catch(IOException e){ 57 e.printStackTrace(); 58 } 59 return jsonObject; 60 } 61 62 /** 63 * post请求 64 * @param url 65 * @param outStr 66 * @return 67 */ 68 public static JSONObject doPostStr(String url,String outStr){ 69 DefaultHttpClient httpClient = new DefaultHttpClient(); 70 HttpPost httpPost = new HttpPost(url); 71 JSONObject jsonObject = null; 72 try{ 73 httpPost.setEntity(new StringEntity(outStr,"UTF-8")); 74 HttpResponse response = httpClient.execute(httpPost); 75 String result = EntityUtils.toString(response.getEntity(),"UTF-8"); 76 jsonObject = JSONObject.fromObject(result); 77 }catch(Exception e){ 78 e.printStackTrace(); 79 } 80 return jsonObject; 81 } 82 /** 83 * 获取access_token 84 * @return 85 */ 86 public static AccessToken getAccessToken(){ 87 AccessToken token = new AccessToken(); 88 String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET); 89 JSONObject jsonObject = doGetStr(url); 90 if(jsonObject != null){ 91 token.setToken(jsonObject.getString("access_token")); 92 token.setExpiresIn(jsonObject.getInt("expires_in")); 93 } 94 System.err.println(jsonObject); 95 return token; 96 } 97 98 /** 99 * 文件上传 100 * @param filePath路径 101 * @param accessToken 102 * @param type 类型 103 * @return 104 * @throws IOException 105 * @throws NoSuchAlgorithmException 106 * @throws NoSuchProviderException 107 * @throws KeyManagementException 108 */ 109 public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { 110 File file = new File(filePath); 111 if (!file.exists() || !file.isFile()) { 112 throw new IOException("文件不存在"); 113 } 114 String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type); 115 URL urlObj = new URL(url); 116 //连接 117 HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); 118 con.setRequestMethod("POST"); 119 con.setDoInput(true); 120 con.setDoOutput(true); 121 con.setUseCaches(false); 122 //设置请求头信息 123 con.setRequestProperty("Connection", "Keep-Alive"); 124 con.setRequestProperty("Charset", "UTF-8"); 125 //设置边界 126 String BOUNDARY = "----------" + System.currentTimeMillis(); 127 con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); 128 StringBuilder sb = new StringBuilder(); 129 sb.append("--"); 130 sb.append(BOUNDARY); 131 sb.append("\r\n"); 132 sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n"); 133 sb.append("Content-Type:application/octet-stream\r\n\r\n"); 134 byte[] head = sb.toString().getBytes("utf-8"); 135 //获得输出流 136 OutputStream out = new DataOutputStream(con.getOutputStream()); 137 //输出表头 138 out.write(head); 139 //文件正文部分 140 //把文件已流文件的方式 推入到url中 141 DataInputStream in = new DataInputStream(new FileInputStream(file)); 142 int bytes = 0; 143 byte[] bufferOut = new byte[1024]; 144 while ((bytes = in.read(bufferOut)) != -1) { 145 out.write(bufferOut, 0, bytes); 146 } 147 in.close(); 148 //结尾部分 149 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线 150 out.write(foot); 151 out.flush(); 152 out.close(); 153 StringBuffer buffer = new StringBuffer(); 154 BufferedReader reader = null; 155 String result = null; 156 try { 157 //定义BufferedReader输入流来读取URL的响应 158 reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 159 String line = null; 160 while ((line = reader.readLine()) != null) { 161 buffer.append(line); 162 } 163 if (result == null) { 164 result = buffer.toString(); 165 } 166 } catch (IOException e) { 167 e.printStackTrace(); 168 } finally { 169 if (reader != null) { 170 reader.close(); 171 } 172 } 173 JSONObject jsonObj = JSONObject.fromObject(result); 174 System.out.println(jsonObj); 175 String typeName = "media_id"; 176 if(!"image".equals(type)){ 177 typeName = type + "_media_id"; 178 } 179 String mediaId = jsonObj.getString(typeName); 180 System.err.println("----"+mediaId); 181 return mediaId; 182 } 183 }
MyX509TrustManager类
1 package com.weixin.util; 2 import java.security.cert.CertificateException; 3 import java.security.cert.X509Certificate; 4 import javax.net.ssl.X509TrustManager; 5 6 /** 7 * 类名: MyX509TrustManager </br> 8 * 描述:信任管理器 </br> 9 * 发布版本:V1.0 </br> 10 */ 11 public class MyX509TrustManager implements X509TrustManager { 12 13 @Override 14 public X509Certificate[] getAcceptedIssuers() { 15 return null; 16 } 17 18 @Override 19 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 20 } 21 22 @Override 23 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 24 } 25 }