Java实现微信公众号模板消息推送功能代码

 微信推送功能精髓之所在

 /**
     *微信模板推送
     * @param req 微信用户唯一标识
     * @param response 处理给浏览器返回的数据
     * @return 返回状态
     */
    @GetMapping("/tuisong")
    public String SendWxNotice(HttpServletRequest req, HttpServletResponse response,String  json) {
        //微信唯一标识
        String openid = GetCookieValue("openid", req);
        //模板id
        String template_id = "NNOBtOS8xzyf6_dMnf_2IZbJ9VqeZ94HYML";
        //声明map
        Map<String, Object> map = new LinkedHashMap<>();
        //传过来json字符串转换成Map
        HashMap jsonToMap = JSON.parseObject(json, HashMap.class);

        map.put("jsonToMap", jsonToMap);
        map.put("touser", openid);
        map.put("template_id", template_id);

//        Map<String, Object> data = new LinkedHashMap<>();
//
//        Map<String, Object> productType = new HashMap<>();
//        productType.put("value","伞");
//        productType.put("color", "#ff0000");
//        data.put("productType", productType);
//
//        Map<String, Object> name = new LinkedHashMap<>();
//        name.put("value", "天花伞");
//        name.put("color", "#ff0000");
//        data.put("name", name);
//
//        Map<String, Object> number = new LinkedHashMap<>();
//        number.put("value", "10");
//        number.put("color", "#ff0000");
//        data.put("number", number);
//
//        Map<String, Object> expDate = new LinkedHashMap<>();
//        expDate.put("value", "2020-07-16");
//        expDate.put("color", "#ff0000");
//        data.put("expDate", expDate);
//
//        Map<String, Object> remark = new LinkedHashMap<>();
//        remark.put("value", "如有疑问,请致电XXXXXXX联系");
//        remark.put("color", "#00ff00");
//        data.put("remark", remark);
//
//        map.put("data", data);
        String str = null;
        try {
            String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.AppId + "&secret=" + this.Secret;
            String getTokenUrlResult = WxUtil.sendGet(getTokenUrl, null);
            JSONObject tokenjson = JSONObject.parseObject(getTokenUrlResult);
            String token = tokenjson.getString("access_token");
            str = WxUtil.sendPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + URLEncoder.encode((token), "UTF-8"), map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

工具类


public class WxUtil {

    private static final String CHAR_SET = "UTF-8";

    public static String sendGet(String url, Map<String,Object> params){
        StringBuilder responseStr = null;
        StringBuilder paramsStr = new StringBuilder();
        if(params != null && params.size() > 0){
            for(Map.Entry<String,Object> entry : params.entrySet()){
                paramsStr.append(entry.getKey());
                paramsStr.append("=");
                try {
                    paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramsStr.append("&");
            }
        }
        URL URLstr = null;
        BufferedReader bufr = null;
        HttpURLConnection httpURLConnection = null;
        try {
            if(paramsStr != null && paramsStr.length() > 0){
                url = url + "?" + paramsStr.substring(0,paramsStr.length() - 1);
            }
            URLstr = new URL(url);
            httpURLConnection = (HttpURLConnection) URLstr.openConnection();
            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            httpURLConnection.connect();
            responseStr = new StringBuilder();
            bufr = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHAR_SET));
            String str = null;
            while((str = bufr.readLine()) != null){
                responseStr.append(str);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            httpURLConnection.disconnect();
            if (bufr != null){
                try {
                    bufr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  responseStr.toString();
    }


    public static String sha1(String data) throws NoSuchAlgorithmException {
        //信息摘要器                                算法名称
        MessageDigest md = MessageDigest.getInstance("SHA1");
        //把字符串转为字节数组
        byte[] b = data.getBytes();
        //使用指定的字节来更新我们的摘要
        md.update(b);
        //获取密文  (完成摘要计算)
        byte[] b2 = md.digest();
        //获取计算的长度
        int len = b2.length;
        //16进制字符串
        String str = "0123456789abcdef";
        //把字符串转为字符串数组
        char[] ch = str.toCharArray();

        //创建一个40位长度的字节数组
        char[] chs = new char[len*2];
        //循环20次
        for(int i=0,k=0;i<len;i++) {
            byte b3 = b2[i];//获取摘要计算后的字节数组中的每个字节
            // >>>:无符号右移
            // &:按位与
            //0xf:0-15的数字
            chs[k++] = ch[b3 >>> 4 & 0xf];
            chs[k++] = ch[b3 & 0xf];
        }

        //字符数组转为字符串
        return new String(chs);
    }

    public  static String sendPost(String urlString, Map<String, Object> params){
        String rs = "";
        String encode = "UTF-8";
        String json = JSON.toJSONString(params);
        try {
            // 建立连接
            URL url = new URL(urlString);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // //设置连接属性
            // 使用 URL 连接进行输出
            httpConn.setDoOutput(true);
            // 使用 URL 连接进行输入
            httpConn.setDoInput(true);
            // 忽略缓存
            httpConn.setUseCaches(false);
            httpConn.setConnectTimeout(50*60*1000);
            httpConn.setReadTimeout(50*60*1000);
            // 设置URL请求方法
            httpConn.setRequestMethod("POST");
            String requestString = "客服端要以以流方式发送到服务端的数据...";
            // 设置请求属性
            // 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
            byte[] requestStringBytes = requestString.getBytes(encode);
 			/*httpConn.setRequestProperty("Content-length", ""
 					+ requestStringBytes.length);
 			httpConn.setRequestProperty("Content-Type",
 					"application/octet-stream");*/
            // 维持长连接
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Charset", encode);
            // 设置文件类型:
            httpConn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
            httpConn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            if (json != null) {
                byte[] writebytes = json.getBytes(encode);
                // 设置文件长度
                httpConn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = httpConn.getOutputStream();
                outwritestream.write(json.getBytes(encode));
                outwritestream.flush();
                outwritestream.close();
            }

            // 建立输出流,并写入数据
            OutputStream outputStream = httpConn.getOutputStream();
            outputStream.write(requestStringBytes);
            outputStream.close();
            // 获得响应状态
            int responseCode = httpConn.getResponseCode();
            // 连接成功
            if (HttpURLConnection.HTTP_OK == responseCode) {
                // 当正确响应时处理数据
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                // 处理响应流,必须与服务器响应流输出的编码一致
                responseReader = new BufferedReader(new InputStreamReader(
                        httpConn.getInputStream(), encode));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }
                responseReader.close();
                rs = sb.toString();
            }
        } catch (Exception ex) {
            System.out.println("httpConnection异常"+ex.toString());
            ex.printStackTrace();
        }
        return rs;


    }
}

  postman测试

{
"data":{
"productType":{"color":"#ff0000","value":"伞"},
"name":{"value":"天花伞","color":"#ff0000"},
"number":{"value":"10","color":"#ff0000"},
"expDate":{"value":"2020-07-16","color":"#ff0000"},
"remark":{"value":"如有疑问,请致电XXXXXXX联系","color":"#00ff00"}
}
}

如能解决你的问题,我会更加努力的

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值