图片消息
```<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<PicUrl><![CDATA[this is a url]]></PicUrl>
<MediaId><![CDATA[media_id]]></MediaId>
<MsgId>1234567890123456</MsgId>
</xml>
参数 描述
ToUserName 开发者微信号
FromUserName 发送方帐号(一个OpenID)
CreateTime 消息创建时间 (整型)
MsgType 消息类型,图片为image
PicUrl 图片链接(由系统生成)
MediaId 图片消息媒体id,可以调用获取临时素材接口拉取数据。
MsgId 消息id,64位整型
```j
校验签名必须要的哦别忘了
Controller:
/**
* 图片消息回复
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = "wx_check",method = {RequestMethod.POST})
public void wxCheck2(HttpServletRequest request, HttpServletResponse response)throws Exception{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter printWriter = response.getWriter();
try {
Map<String, String> map = MessageUtil.xmlToMap(request);
String toUserName = map.get("ToUserName");
String fromUserName = map.get("FromUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
String message = null;
if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
/**
* 图片消息回复
*/
message= MessageUtil.initNewsMessage(toUserName,fromUserName);
}
System.out.print(message);
printWriter.print(message);
}catch (DocumentException e){
e.printStackTrace();
}finally {
printWriter.close();
}
}
MessageUtil:
public static final String MESSAGE_TEXT = "text";//文本消息
public static final String MESSAGE_IMAGE = "image";//图片消息
public static final String MESSAGE_VOICE = "voice";//语音消息
public static final String MESSAGE_VIDEO = "video";//视频
public static final String MESSAGE_SHORTVIDEO = "shortvideo";//小视屏
public static final String MESSAGE_LOCATION = "location";//地理位置
public static final String MESSAGE_LINK = "link";//链接
public static final String MESSAGE_EVENT = "event";//事件推送
public static final String MESSAGE_SUBSCRIBE = "subscribe";//被关注
public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";//取消关注
public static final String MESSAGE_CLICK = "CLICK";//点击
public static final String MESSAGE_VIEW = "VIEW";//
/**
* 图片消息组装
* @param toUserName
* @param fromUserName
* @return
*/
public static String initNewsMessage (String toUserName, String fromUserName)throws Exception{
String message = null;
Image image = new Image();
AccessToken token = WeiXinUtil.getAccessToken();
System.out.print("票据:"+token.getToken());
System.out.print("有效时间:"+token.getExpiresIn());
image.setMediaId(WeiXinUtil.upload("img/0.jpg",token.getToken(),"image"));
ImageMessage imageMessage = new ImageMessage();
imageMessage.setFromUserName(toUserName);
imageMessage.setToUserName(fromUserName);
imageMessage.setMsgType(MESSAGE_IMAGE);
imageMessage.setCreateTime(new Date().getTime()+"");
imageMessage.setImage(image);
message = imageMessageToxml(imageMessage);
return message;
}
Image:
package com.jl.controller.po;
public class Image {
private String MediaId;
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
}
ImageMessage:
package com.jl.controller.po;
public class ImageMessage extends BaseMessage {
private Image Image;
public com.jl.controller.po.Image getImage() {
return Image;
}
public void setImage(com.jl.controller.po.Image image) {
Image = image;
}
}
AccessToken:
package com.jl.controller.po;
public class AccessToken {
private String token;
private int expiresIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
BaseMessage:
package com.jl.controller.po;
public class BaseMessage {
private String ToUserName;
private String FromUserName;
private String CreateTime;
private String MsgType;
private String MediaId;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
}
WeiXinUtil:
private static final String APPID = "写自己的";
private static final String APPSECRET = "写自己的";
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
/**
* get请求
* @param url
* @return
* @throws ParseException
* @throws IOException
*/
public static JSONObject doGetStr(String url) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse httpResponse = client.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
return jsonObject;
}
/**
* POST请求
* @param url
* @param outStr
* @return
* @throws ParseException
* @throws IOException
*/
public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
httpost.setEntity(new StringEntity(outStr,"UTF-8"));
HttpResponse response = client.execute(httpost);
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
jsonObject = JSONObject.fromObject(result);
return jsonObject;
}
(下载图片获得mediaid)
/**
* 文件下载
* @param filePath
* @param accessToken
* @param type
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
URL urlObj = new URL(url);
//连接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
//设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
//获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
//输出表头
out.write(head);
//文件正文部分
//把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
//结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String result = null;
try {
//定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
JSONObject jsonObj = JSONObject.fromObject(result);
System.out.println(jsonObj);
String typeName = "media_id";
if(!"image".equals(type)){
typeName = type + "_media_id";
}
String mediaId = jsonObj.getString(typeName);
return mediaId;
}
/**
* 获取accessToken
* @return
* @throws ParseException
* @throws IOException
*/
public static AccessToken getAccessToken() throws ParseException, IOException{
AccessToken token = new AccessToken();
String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
JSONObject jsonObject = doGetStr(url);
if(jsonObject!=null){
token.setToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
}
return token;
}
MessageUtil:
/**
* 将图片对象转换为xml
*
* @param imageMessage
* @return
*/
public static String imageMessageToxml(ImageMessage imageMessage) {
XStream xStream = new XStream(http://www.amjmh.com/v/);
xStream.alias("xml", imageMessage.getClass());
return xStream.toXML(imageMessage);
}