微信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 }

 

 

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 }

 

转载于:https://www.cnblogs.com/a757956132/p/5411483.html

<think>好的,用户想了解在微信开发者工具中如何发出POST请求。首先,我需要回忆一下微信小程序的网络请求相关API。微信小程序使用的是wx.request这个API来发起网络请求,无论是GET还是POST。 接下来,用户特别提到POST请求,所以需要强调method参数要设置为'POST'。同时,POST请求通常需要发送数据,所以data参数是必须的。这里要提醒用户正确设置请求头,尤其是Content-Type,比如application/json或者application/x-www-form-urlencoded,否则后端可能无法正确解析数据。 然后,我需要考虑微信的安全限制,比如域名必须在小程序后台的合法域名列表中,否则在真机上无法请求,但在开发者工具中可以勾选不校验域名。这一点很重要,用户可能会遇到这个问题,需要提前告知。 另外,示例代码是关键,用户可能需要一个简单的模板来参考。要确保代码中的url替换成实际的接口地址,并且处理成功和失败的回调。同时,ES6的箭头函数可能会让代码更简洁,但也要考虑到用户可能对箭头函数不太熟悉,所以是否需要注释说明?不过通常示例代码简洁明了更重要。 还要提到wx.request返回的是一个task对象,可以用于取消请求,但一般情况可能用不到,所以可能暂时不需要深入。但如果有高级用法,可以简单带过。 可能还需要比较一下wx.request和其他库的区别,比如小程序是否支持axios,但根据官方文档,应该是不支持的,只能使用wx.request或者封装后的库。这一点如果有用户问起再详细说明,现在可能不需要。 最后,常见的问题比如跨域问题在开发者工具中可以临时解决,但上线前必须配置合法域名。此外,SSL证书的问题也需要考虑,即接口必须是HTTPS的。这些都是在开发过程中容易遇到的坑,需要提醒用户注意。 总结一下,回答的结构应该是先介绍wx.request的基本用法,然后重点说明POST请求的参数设置,提供示例代码,最后补充注意事项和常见问题。这样用户能够一步步按照指导实现POST请求,同时避免常见错误。</think>在微信开发者工具中发出 POST 请求,主要通过小程序提供的 `wx.request` API 实现。以下是详细步骤和注意事项: --- ### 一、基础实现代码 ```javascript wx.request({ url: 'https://example.com/api', // 替换为你的接口地址 method: 'POST', data: { key1: 'value1', key2: 'value2' }, header: { 'content-type': 'application/json' // 根据接口要求选择格式 }, success(res) { console.log('请求成功:', res.data) }, fail(err) { console.error('请求失败:', err) } }) ``` --- ### 二、关键参数说明 1. **url**(必填): - 必须是 HTTPS 协议 - 域名需在小程序后台的「开发设置」-「服务器域名」中配置(开发阶段可在开发者工具勾选「不校验合法域名」) 2. **method**: - 明确指定为 `'POST'`(默认是 GET) 3. **data**: - POST 请求的 body 数据 - 支持 `Object`/`String`/`ArrayBuffer` 格式 4. **header**: - 常见设置: ```javascript 'content-type': 'application/json' // JSON 格式 // 或 'content-type': 'application/x-www-form-urlencoded' // 表单格式 ``` --- ### 三、完整示例(带 Promise 封装) ```javascript const postRequest = (url, data) => { return new Promise((resolve, reject) => { wx.request({ url, method: 'POST', data, header: { 'Content-Type': 'application/json' }, success: (res) => { if (res.statusCode === 200) { resolve(res.data) } else { reject(res) } }, fail: reject }) }) } // 使用示例 postRequest('https://api.example.com/login', { username: 'admin', password: '123456' }).then(res => { console.log('登录成功:', res) }).catch(err => { console.error('登录失败:', err) }) ``` --- ### 四、常见问题排查 1. **跨域问题**: - 开发环境:勾选开发者工具右上角「详情」-「本地设置」-「不校验合法域名...」 - 生产环境:必须在小程序后台配置服务器域名 2. **Content-Type 不匹配**: - 如果后端要求 `x-www-form-urlencoded`,需转换数据格式: ```javascript data: 'key1=value1&key2=value2', header: { 'Content-Type': 'application/x-www-form-urlencoded' } ``` 3. **HTTPS 强制要求**: - 所有请求必须使用 HTTPS,本地调试可通过内网穿透工具实现 4. **数据大小限制**: - 默认 POST 数据最大 1MB,超限需分片上传 --- ### 五、高级功能 1. **上传文件**: ```javascript wx.uploadFile({ url: 'https://example.com/upload', filePath: tempFilePath, // 本地文件路径 name: 'file', formData: { extra: 'data' }, success(res) { console.log('上传成功:', res.data) } }) ``` 2. **中断请求**: ```javascript const task = wx.request({...}) // 需要时调用 task.abort() ``` 建议通过开发者工具的「Network」面板实时监控请求详情,这是调试网络请求的重要工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值