微信小程序模板消息发送成功但显示空白总结Java后台

版权声明: https://blog.csdn.net/weixin_41716049/article/details/84099434

小程序地图导航,显示天气源码  https://github.com/zzwwjjdj319/miniProgramAmap

信微小猜拳游戏程序源码小https://gitee.com/sccqcd/wechat_applet_weather_map

微信小程序机票查询源码:https://gitee.com/sccqcd/ticket_inquiries

最近在做小程序模板消息发送,开始测试的时候直接在微信开发工具发的请求的,数据一切正常,柯林斯详情看我的另一个博文https://blog.csdn.net/weixin_41716049/article/details / 84066595,优劣上面都写的很清楚了,现在写一下java后台发送模板消息时遇到的问题吧,先看我最开始的代码,直接根据模板信息拼接了一个字符串然后测试的时候发现这个请求只接受JSON数据格式然后又转了JSON格式传过去(HttpRequest的工具类我一会放在最下面,有需要的键看看),然后问题出现了,发的模板消息成功了,但是就是没有数据显示出来,网上找了好久,很多人说是大括号里有空格的问题(大家自己先检查检查额),检查后没有问题,然后想到一个问题,是不是JSON数据出问题了,把数据打印出来去JSON校验没问题,尴尬中.....最后突然想起

传入的JSON包,不仅外面是JSON格式,里面的也需要是JSON。然后就换了一种写法,用JSON进行封装数据再传递下面请看代码

 public String publishModelMessage(Meeting meeting){
	      try {
			String openId = meeting.getOpenID();
			  String UserToken= mettingService.getUserToken();
  String params ="{\"touser\":"+openId+
			 ",\"template_id\":\"xNVc7oTpYpnSEduciZoiWcJAl64fifPve49UGa9EwSU\""+
			 ",\"page\":\"pages/pages/created/created\""+
			 ",\"form_id\":"+"\"dde5d9de4dc9ac29eb5c851e004127c9\""+","+
			 "\"date\":{\"keyword1\""+": "+"{"+"\"value\""+":"+ meeting.getSubjectlogin()+","+"\"color\""+":\"#4a4a4a\"},"+
			 "\"keyword2\""+": "+"{"+"\"value\""+":"+ meeting.getSubjectUser()+","+"\"color\""+":\"#9b9b9b\"},"+
			 "\"keyword3\""+": "+"{"+"\"value\""+":"+ meeting.getMeetingDate()+","+"\"color\""+":\"#9b9b9b\"},"+
			 "\"keyword4\""+": "+"{"+"\"value\""+":"+ meeting.getInputSite()+","+"\"color\""+":\"#9b9b9b\"}}}";
			    // 发送请求
            JSONObject json = new JSONObject(params);  
            System.out.println("=================="+json+"============");
	String sr = HttpRequest.jsonPost("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+UserToken, json); 
			    System.out.println("=================="+sr+"============");
				return sr;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "模板消息发送失败";
		}
	      
	 }

修改后代码如下,跑一遍后嗯哼完美,终于有数据了,总结:做事不要看表面,

 public String publishModelMessage(Meeting meeting){
	      try {
			String openId = meeting.getOpenID();
			  String UserToken= mettingService.getUserToken();

            JSONObject _data = new JSONObject();
    		
            JSONObject keyword1 = new JSONObject();	
            keyword1.put("value",meeting.getSubjectlogin());
            keyword1.put("color", "#4a4a4a");	
            _data.put("keyword1",keyword1);
            		
            JSONObject keyword2 = new JSONObject();	
            keyword2.put("value", meeting.getSubjectUser());
            keyword2.put("color", "#9b9b9b");	
            _data.put("keyword2",keyword2);
            		
            JSONObject keyword3 = new JSONObject();	
            keyword3.put("value", meeting.getMeetingDate());
            keyword3.put("color", "#9b9b9b");	
            _data.put("keyword3",keyword3);
            		
            JSONObject keyword4 = new JSONObject();	
            keyword4.put("value", meeting.getInputSite());
            keyword4.put("color", "#9b9b9b");
            _data.put("keyword4",keyword4);
            
            JSONObject _message = new JSONObject();
            		
           
            		
            _message.put("template_id", "###############################");
            
            _message.put("touser", openId);
            
            _message.put("page", "pages/index/index");
            
            _message.put("form_id", meeting.getfId());
            		
            _message.put("data", _data);
            		
           
            System.out.println("----------"+_message);		
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + UserToken;
            		
            String result = HttpRequest.jsonPost(url,_message );
            System.out.println("====="+result);
            return result;
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "模板消息发送失败";
		}
	      

	      
			
	  
	     
	 }
	 

我把我的请求工具类发给大家吧一个GET请求两个POST请求(分别是传字符串,传JSON的)

package com.liruan.zztg.util;
 
import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
import java.net.URL;  
import java.net.URLConnection;  
import java.util.List;  
import java.util.Map;

import org.json.JSONObject;  
  
public class HttpRequest {  
  
    public static void main(String[] args) {  
        //发送 GET 请求  
        String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");  
        System.out.println(s);  
  
//        //发送 POST 请求  
//        String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");  
//        JSONObject json = JSONObject.fromObject(sr);  
//        System.out.println(json.get("data"));  
    }  
  
    /** 
     * 向指定URL发送GET方法的请求 
     *  
     * @param url 
     *            发送请求的URL 
     * @param param 
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 
     * @return URL 所代表远程资源的响应结果 
     */  
    public static String sendGet(String url, String param) {  
        String result = "";  
        BufferedReader in = null;  
        try {  
            String urlNameString = url + "?" + param;  
            URL realUrl = new URL(urlNameString);  
            // 打开和URL之间的连接  
            URLConnection connection = realUrl.openConnection();  
            // 设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 建立实际的连接  
            connection.connect();  
            // 获取所有响应头字段  
            Map<String, List<String>> map = connection.getHeaderFields();  
            // 遍历所有的响应头字段  
            for (String key : map.keySet()) {  
                System.out.println(key + "--->" + map.get(key));  
            }  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送GET请求出现异常!" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        return result;  
    }  
  
    /**  
     * 向指定 URL 发送POST方法的请求  
     *   
     * @param url  
     *            发送请求的 URL  
     * @param param  
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
     * @return 所代表远程资源的响应结果  
     */  
    public static String sendPost(String url, String param) {  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());  
            // 发送请求参数  
            
            out.print(param);  
            // flush输出流的缓冲  
            out.flush();  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(  
                    new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送 POST 请求出现异常!"+e);  
            e.printStackTrace();  
        }  
        //使用finally块来关闭输出流、输入流  
        finally{  
            try{  
                if(out!=null){  
                    out.close();  
                }  
                if(in!=null){  
                    in.close();  
                }  
            }  
            catch(IOException ex){  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }
    /**  
     * 向指定 URL 发送POST方法的请求  
     *   
     * @param url  
     *            发送请求的 URL  
     * @param param  
     *            请求参数,请求参数应该是 json 的形式。  
     * @return 所代表远程资源的响应结果  
     */ 
	public static String jsonPost(String url, JSONObject json) {
		PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());  
            // 发送请求参数  
            
            out.print(json);  
            // flush输出流的缓冲  
            out.flush();  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(  
                    new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送 POST 请求出现异常!"+e);  
            e.printStackTrace();  
        }  
        //使用finally块来关闭输出流、输入流  
        finally{  
            try{  
                if(out!=null){  
                    out.close();  
                }  
                if(in!=null){  
                    in.close();  
                }  
            }  
            catch(IOException ex){  
                ex.printStackTrace();  
            }  
        }  
        return result; 
	}      
} 

猜你喜欢

转载自blog.csdn.net/weixin_41716049/article/details/84099434