微信get post请求到微信服务器 模版 素材操作

1:素材管理

  官方文档

package org.konghao.weixin.media;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.konghao.basic.util.JsonUtil;
import org.konghao.weixin.json.WeixinMedia;
import org.konghao.weixin.model.WeixinFinalValue;
import org.konghao.weixin.quartz.RefreshAccessTokenTask;

public class MediaKit {

    public static String postMedia(String path,String type) {
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        
        try {
            client = HttpClients.createDefault();
            String url = WeixinFinalValue.POST_MEDIA;
            url = url.replace("ACCESS_TOKEN", RefreshAccessTokenTask.refreshToken());
            url = url.replace("TYPE", type);
            HttpPost post = new HttpPost(url);
            FileBody fb = new FileBody(new File(path));
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("media", fb).build();
            post.setEntity(reqEntity);
            resp = client.execute(post);
            int sc = resp.getStatusLine().getStatusCode();
            if(sc>=200&&sc<300) {
                String json = EntityUtils.toString(resp.getEntity());
                System.out.println(json);
                WeixinMedia wm = (WeixinMedia)JsonUtil.getInstance().json2obj(json, WeixinMedia.class);
                return wm.getMedia_id();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    public static void getMedia(String mediaId,File f) {
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        
        try {
            client = HttpClients.createDefault();
            String url = WeixinFinalValue.GET_MEDIA;
            url = url.replace("ACCESS_TOKEN", RefreshAccessTokenTask.refreshToken());
            url = url.replace("MEDIA_ID", mediaId);
            HttpGet get = new HttpGet(url);
            resp = client.execute(get);
            int sc = resp.getStatusLine().getStatusCode();
            if(sc>=200&&sc<300) {
                InputStream is = resp.getEntity().getContent();
                System.out.println(resp.toString());
                FileUtils.copyInputStreamToFile(is, f);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.1 调用方法:

 1     
 2     //上传素材
 3     @Test
 4     public void testPostMedia() {
 5         String mid = MediaKit.postMedia("C:\Users\Public\Pictures\Sample Pictures\aa.jpg","image");
 6         System.out.println(mid);
 7     }
 8     
 9     //获取素材
10     @Test
11     public void testGetMedia() {
12         try {
13             String mid = MediaKit.postMedia("C:\Users\Public\Pictures\Sample Pictures\aa.jpg","image");
14             MediaKit.getMedia(mid,new File("C:\Users\Public\Pictures\Sample Pictures\x.jpg"));
15         } catch (Exception e) {
16             e.printStackTrace();
17         }
18     }
19     

2 : 模版测试

  官方参考文档

  2.1 实体类

 1 package org.konghao.weixin.json;
 2 
 3 import java.util.Map;
 4 
 5 public class TemplateMsg {
 6     
 7     private String touser ; 
 8     private String template_id;
 9     private String url ; 
10     private String topcolor ; 
11     private Map<String, Object> data;
12     public String getTouser() {
13         return touser;
14     }
15     public void setTouser(String touser) {
16         this.touser = touser;
17     }
18     public String getTemplate_id() {
19         return template_id;
20     }
21     public void setTemplate_id(String template_id) {
22         this.template_id = template_id;
23     }
24     public String getUrl() {
25         return url;
26     }
27     public void setUrl(String url) {
28         this.url = url;
29     }
30     public String getTopcolor() {
31         return topcolor;
32     }
33     public void setTopcolor(String topcolor) {
34         this.topcolor = topcolor;
35     }
36     public Map<String, Object> getData() {
37         return data;
38     }
39     public void setData(Map<String, Object> data) {
40         this.data = data;
41     }
42 
43 }

  2.2测试类

 1     //测试模板消息I
 2     @Test
 3     public void testPostTemplateMsg(){
 4         TemplateMsg tm = new TemplateMsg();
 5         tm.setTouser("oUigKxHuNI-QMHKzvyYpw1lCY8VQ");//接受者的微信号
 6         tm.setTemplate_id("eeXrrEtSncwNZ8P1uZnKXpB8jqNbI1-usso5Ifp-Ow0");//模版id
 7         tm.setTopcolor("#ff0000");
 8         tm.setUrl("http://www.konghao.org/index");
 9         Map<String, Object> data = new HashMap<String, Object>();
10         data.put("num", new ModelMsgData("123" , "#00ff00"));
11         tm.setData(data);
12         System.out.println("TemplateMsg json:" + JsonUtil.getInstance().obj2json(tm));
13         
14         MessageKit.postTemplateMsg(tm);
15     }

  2.3 模版工具类

  1 package org.konghao.weixin.msg;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.io.StringWriter;
  7 import java.util.Date;
  8 import java.util.HashMap;
  9 import java.util.List;
 10 import java.util.Map;
 11 import java.util.Set;
 12 
 13 import javax.servlet.http.HttpServletRequest;
 14 
 15 import org.apache.http.client.ClientProtocolException;
 16 import org.apache.http.client.methods.CloseableHttpResponse;
 17 import org.apache.http.client.methods.HttpPost;
 18 import org.apache.http.entity.ContentType;
 19 import org.apache.http.entity.StringEntity;
 20 import org.apache.http.impl.client.CloseableHttpClient;
 21 import org.apache.http.impl.client.HttpClients;
 22 import org.apache.http.util.EntityUtils;
 23 import org.dom4j.Document;
 24 import org.dom4j.DocumentException;
 25 import org.dom4j.DocumentHelper;
 26 import org.dom4j.Element;
 27 import org.dom4j.io.XMLWriter;
 28 import org.konghao.basic.util.JsonUtil;
 29 import org.konghao.weixin.json.TemplateMsg;
 30 import org.konghao.weixin.kit.WeixinKit;
 31 import org.konghao.weixin.model.WeixinFinalValue;
 32 import org.konghao.weixin.quartz.RefreshAccessTokenTask;
 33 
 34 public class MessageKit {
 35     private static Map<String,String> replyMsgs = new HashMap<String,String>();
 36     static{
 37         replyMsgs.put("123", "你输入了123");
 38         replyMsgs.put("hello", "world");
 39         replyMsgs.put("run", "祝你一路平安!");
 40     }
 41     
 42     @SuppressWarnings("unchecked")
 43     public static Map<String,String> reqMsg2Map(HttpServletRequest req) throws IOException {
 44         String xml = req2xml(req);
 45         System.out.println("xml字符串:" + xml);
 46         try {
 47             Map<String,String> maps = new HashMap<String, String>();
 48             Document document = DocumentHelper.parseText(xml);
 49             Element root = document.getRootElement();
 50             List<Element> eles = root.elements();
 51             for(Element e:eles) {
 52                 maps.put(e.getName(), e.getTextTrim());
 53             }
 54             return maps;
 55         } catch (DocumentException e) {
 56             e.printStackTrace();
 57         }
 58         return null;
 59     }
 60     
 61     private static String req2xml(HttpServletRequest req) throws IOException {
 62         BufferedReader br = null;
 63         br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
 64         String str = null;
 65         StringBuffer sb = new StringBuffer();
 66         while((str=br.readLine())!=null) {
 67             sb.append(str);
 68         }
 69         return sb.toString();
 70     }
 71     
 72     public static String handlerMsg(Map<String, String> msgMap) throws IOException {
 73         String msgType = msgMap.get("MsgType");
 74         if(msgType.equals(WeixinFinalValue.MSG_EVENT_TYPE)) {
 75             
 76         } else if(msgType.equals(WeixinFinalValue.MSG_TEXT_TYPE)) {
 77             return textTypeHandler(msgMap);
 78         } else if(msgType.equals(WeixinFinalValue.MSG_IMAGE_TYPE)) {
 79             return imageTypeHandler(msgMap,msgMap.get("MediaId"));
 80         }
 81         return null;
 82     }
 83     
 84     private static String imageTypeHandler(Map<String, String> msgMap,String mediaId) throws IOException {
 85         Map<String,String> map = new HashMap<String, String>();
 86         map.put("ToUserName", msgMap.get("FromUserName"));
 87         map.put("FromUserName", msgMap.get("ToUserName"));
 88         map.put("CreateTime", new Date().getTime()+"");
 89         map.put("MsgType", "image");
 90         System.out.println("mediaId:" + mediaId);
 91         map.put("Image", "<MediaId>"+mediaId+"</MediaId>");
 92         return map2xml(map);
 93     }
 94     
 95     private static String textTypeHandler(Map<String, String> msgMap) throws IOException {
 96         Map<String,String> map = new HashMap<String, String>();
 97         map.put("ToUserName", msgMap.get("FromUserName"));
 98         map.put("FromUserName", msgMap.get("ToUserName"));
 99         map.put("CreateTime", new Date().getTime()+"");
100         map.put("MsgType", "text");
101         String replyContent = "你请求的消息的内容不正确!";
102         String con = msgMap.get("Content");
103         if(replyMsgs.containsKey(con)) {
104             replyContent = replyMsgs.get(con);
105         }
106         map.put("Content", replyContent);
107         return map2xml(map);
108     }
109     
110     public static String map2xml(Map<String, String> map) throws IOException {
111         Document d = DocumentHelper.createDocument();
112         Element root = d.addElement("xml");
113         Set<String> keys = map.keySet();
114         for(String key:keys) {
115             root.addElement(key).addText(map.get(key));
116         }
117         StringWriter sw = new StringWriter();
118         //d.write(sw);//会造成标签被转义  , 改进方法
119         XMLWriter xw = new XMLWriter(sw);
120         xw.setEscapeText(false);
121         xw.write(d);
122         
123         return sw.toString();
124     }
125     
126     
127     //测试类使用方法:模板消息
128     public static String postTemplateMsg(TemplateMsg tm) {
129         CloseableHttpClient client = null;
130         CloseableHttpResponse response = null;
131         try {
132             client = HttpClients.createDefault();
133             String url = WeixinFinalValue.SEND_TEMPLATE_MSG ; 
134             url = url.replace("ACCESS_TOKEN", RefreshAccessTokenTask.refreshToken());
135             HttpPost post = new HttpPost(url);
136             String json = JsonUtil.getInstance().obj2json(tm);
137             post.addHeader("Content-Type","application/json");
138             StringEntity entity = new StringEntity(json , ContentType.create("application/json", "utf-8"));
139             post.setEntity(entity);
140             response = client.execute(post);
141             int statusCode = response.getStatusLine().getStatusCode();
142             if(statusCode >= 200 && statusCode < 300){
143                 String str = EntityUtils.toString(response.getEntity());
144                 System.out.println(str);
145                 return str ; 
146         }
147         } catch (ClientProtocolException e) {
148             e.printStackTrace();
149         } catch (IOException e) {
150             e.printStackTrace();
151         }
152         return null;
153     }
154     
155     //模板消息
156     public static String postTemplateMsg2(TemplateMsg tm) {
157         CloseableHttpClient client = null;
158         CloseableHttpResponse response = null;
159         String url = WeixinFinalValue.SEND_TEMPLATE_MSG;
160         url = url.replace("ACCESS_TOKEN", RefreshAccessTokenTask.at);
161         String json = JsonUtil.getInstance().obj2json(tm);
162         return WeixinKit.postReq(url, json, "application/json");
163     }
164 }

 微信get post请求到微信服务器              模版 素材操作

 微信get post请求到微信服务器              模版 素材操作

3 微信相关常量url

 1 package org.konghao.weixin.model;
 2 
 3 public class WeixinFinalValue {
 4     public final static String APPID = "wxb6cb4dfef6995d43";
 5     public final static String APPSECRET = "e069099f1e9d95794c1b015d216a50f6";
 6     public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
 7     public final static String MENU_ADD = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
 8     
 9     public final static String MSG_TEXT_TYPE = "text";
10     public final static String MSG_IMAGE_TYPE = "image";
11     public final static String MSG_VOICE_TYPE = "voice";
12     public final static String MSG_VIDEO_TYPE = "video";
13     public final static String MSG_SHORTVIDEO_TYPE = "shortvideo";
14     public final static String MSG_LOCATION_TYPE = "location";
15     public final static String MSG_EVENT_TYPE = "event";
16     
17     //素材管理 : 新增临时素材
18     public final static String POST_MEDIA="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
19     //素材管理 :获取临时素材
20     public final static String GET_MEDIA="https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
21     
22     //消息管理  发送模板消息
23     public final static String SEND_TEMPLATE_MSG = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
24 
25     //用户
26     public final static String ADD_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN";
27     public final static String QUERY_ALL_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN";
28     public final static String QUERY_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN";
29     public final static String UPDATE_GROUP_NAME = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN";
30     public final static String MOVE_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=ACCESS_TOKEN";
31     public final static String MOVE_USERS_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=ACCESS_TOKEN";
32     public final static String DELETE_GROUP_USER = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=ACCESS_TOKEN";
33     
34     
35 }