Micro-channel format photo Reply

Picture messages

```<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>

Parameter Description
ToUserName developer Micro Signal
FromUserName sender account (a the OpenID)
CreateTime message creation time (integer)
MsgType message type, Photo Image
PicUrl picture link (generated by the system)
MediaId picture messaging media id, you can call to get temporary material interfaces pull data.
MsgId message id, 64-bit integer
`` `j
verify the signature must be oh do not forget
the Controller:
/ **
* Picture Message reply
* @param Request
* @param the Response
* @throws Exception
* /
@ RequestMapping (value = "wx_check", Method RequestMethod.POST = {})
public void wxCheck2 (the HttpServletRequest Request, the HttpServletResponse Response) throws Exception {
Request.setCharacterEncoding ( "UTF-. 8");
response.setCharacterEncoding ( "UTF-. 8");
the PrintWriter a PrintWriter = response.getWriter ();
the 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)) {

/ **
* Image reply message
* /
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 ImageMessage = new ();
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);

// setup request header
con.setRequestProperty ( "Connection", "the Keep-Alive");
con.setRequestProperty ( "the 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");

// obtain an output stream
the OutputStream the DataOutputStream new new OUT = (con.getOutputStream ());
// output meters
out.write (head);

The body of the file //
// manner file stream file is pushed into the url
DataInputStream in = new new DataInputStream (new new the FileInputStream (File));
int = 0 bytes;
byte [] = BUFFEROUT new new byte [1024];
the while ( (bytes = in.read (BUFFEROUT)) = -1) {!
out.write (BUFFEROUT, 0, bytes);
}
in.close ();

// end of
byte [] foot = ( "\ r \ n--" + BOUNDARY + "- \ r \ n") getBytes ( "utf-8"); // define the final data divider.

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);
}

 

Guess you like

Origin www.cnblogs.com/liyanyan665/p/11414338.html