微信公众平台深度开发JAVA版第一季 31.菜单7

上一节讲完了构建自定义菜单,自定义菜单创建接口那一块.这一节讲自定义菜单查询接口.创建自定义菜单和得到自定义菜单的报文也结束了.

112046_uxWx_3206447.png

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx51d48729cf5ce7ce&secret=5b14c8d2cb46ddc389936cdb135f18ac
{"access_token":"OTbn21WBtq2j6FpyCHyWV-K5aZggw3b3m1gMd_fiU8gfc6zjRiVoolRkIlYdJzGAWiXYJvH8mCMsE2Mnc14gKOAuKsyRRn9IzJpfDdw8j-8GTBiABABOW","expires_in":7200}
OTbn21WBtq2j6FpyCHyWV-K5aZggw3b3m1gMd_fiU8gfc6zjRiVoolRkIlYdJzGAWiXYJvH8mCMsE2Mnc14gKOAuKsyRRn9IzJpfDdw8j-8GTBiABABOW
{"errcode":0,"errmsg":"ok"}
{"errcode":0,"errmsg":"ok"}
{"errcode":0,"errmsg":"ok"}
{"button":[{ "type": "click",        "name": "说明001",                 "key": "001"              },{ "type": "view",        "name": "说明002",  "url": "http://www.baidu.com/"              },    {  "name":"sub_caidan001", "sub_button":[ { "type": "click",        "name": "下级001",                 "key": "sub001"              },{ "type": "view",        "name": "下级002",  "url": "http://www.baidu.com/"              }        ]               }       ]}
{"menu":{"button":[{"type":"click","name":"说明001","key":"001","sub_button":[]},{"type":"view","name":"说明002","url":"http:\/\/www.baidu.com\/","sub_button":[]},{"name":"sub_caidan001","sub_button":[{"type":"click","name":"下级001","key":"sub001","sub_button":[]},{"type":"view","name":"下级002","url":"http:\/\/www.baidu.com\/","sub_button":[]}]}]}}
{"button":[{ "type": "click",        "name": "说明001",                 "key": "001"              },{ "type": "view",        "name": "说明002",  "url": "http://www.baidu.com/"              },    {  "name":"sub_caidan001", "sub_button":[ { "type": "click",        "name": "下级001",                 "key": "sub001"              },{ "type": "view",        "name": "下级002",  "url": "http://www.baidu.com/"              }        ]               }       ]}
{"menu":{"button":[{"type":"click","name":"说明001","key":"001","sub_button":[]},{"type":"view","name":"说明002","url":"http:\/\/www.baidu.com\/","sub_button":[]},{"name":"sub_caidan001","sub_button":[{"type":"click","name":"下级001","key":"sub001","sub_button":[]},{"type":"view","name":"下级002","url":"http:\/\/www.baidu.com\/","sub_button":[]}]}]}}

create的报文和query的报文是不一样的。

从程序的角度query()方法返回回来的最好不是一个字符串,而是一个菜单对象.create的报文和query的报文的结构是不一样的,如果想query和create的报文都支持的话那样bean的构建就需要功底了.

132429_1xAB_3206447.png

每一个接口都是不一样的,只有你敲一遍你才知道它问题出现在哪里。就像之前读取信息流的报文的大小写写错了,你不敲代码你是看不出来的。

JDBC的读取数据库的流的关闭和I/O文件流的关闭都是有顺序的.

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx51d48729cf5ce7ce&secret=5b14c8d2cb46ddc389936cdb135f18ac
{"access_token":"xafvaGdfthmsOHDSsOFMAf4CRUC64iXt-6ybrbD1VGA9f3_6_bImIs5Ve3UCUHcdp-5qNCaTH1srsHkBDznSKv2gSOUqop6ZGvDdtFpZ7LL_yyMxkqu3-4p-vBJJei1JNCYeACAJYU","expires_in":7200}
xafvaGdfthmsOHDSsOFMAf4CRUC64iXt-6ybrbD1VGA9f3_6_bImIs5Ve3UCUHcdp-5qNCaTH1srsHkBDznSKv2gSOUqop6ZGvDdtFpZ7LL_yyMxkqu3-4p-vBJJei1JNCYeACAJYU
{"errcode":0,"errmsg":"ok"}
{"errcode":0,"errmsg":"ok"}
{"errcode":0,"errmsg":"ok"}
{"button":[{ "type": "click",        "name": "说明001",                 "key": "001"              },{ "type": "view",        "name": "说明002",  "url": "http://www.baidu.com/"              },    {  "name":"sub_caidan001", "sub_button":[ { "type": "click",        "name": "下级001",                 "key": "sub001"              },{ "type": "view",        "name": "下级002",  "url": "http://www.baidu.com/"              }        ]               }       ]}
{"menu":{"button":[{"type":"click","name":"说明001","key":"001","sub_button":[]},{"type":"view","name":"说明002","url":"http:\/\/www.baidu.com\/","sub_button":[]},{"name":"sub_caidan001","sub_button":[{"type":"click","name":"下级001","key":"sub001","sub_button":[]},{"type":"view","name":"下级002","url":"http:\/\/www.baidu.com\/","sub_button":[]}]}]}}
{"errcode":0,"errmsg":"ok"}
package wx.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import bean.caidan.CaiDan;

public class WX_CaiDan {
	/**
	 * 
	 * @param access_token
	 * @return
	 */
	public static String delete(String access_token) {
		StringBuffer strb = new StringBuffer();
		
		try {
			/*连接URL*/
			URL url =  new URL("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+access_token);
			
			HttpURLConnection connection=   (HttpURLConnection) url.openConnection();  
			/*得到in*/
			InputStream in = connection.getInputStream();
			/*得到reader*/
			InputStreamReader reader = new InputStreamReader(in);
			/*得到reader*/
			BufferedReader breader = new BufferedReader(reader);//做字符流和字节流的转换
			String str = null;
			while(null != (str = breader.readLine())){
				strb.append(str);
			}
			/*关闭breader*/
			breader.close();
			/*关闭reader*/
			reader.close();
			/*关闭in*/
			in.close();
		} 
		//catch (MalformedURLException e) {
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return strb.toString();//
	}
	
	
	/**
	 * 查询菜单
	 * @param access_token
	 * @return
	 */
	public static String query(String access_token){//查询接口也要传递ACCESS_TOKEN
		StringBuffer strb  =  new StringBuffer();
		//StringBuilder和StringBuffer它们之间是有区别的.区别主要是安全性那块.微信开发这块区别不大,无所谓,但是这些知识还是要多了解下.
		//网络操作这个过程在微信开发这块非常重要.后期很多东西都是通过网络来实现了.
		InputStream in = null;//
		InputStreamReader reader = null;//
		BufferedReader breader = null;//编程的经验,对程序知道怎么弄更好一些
		try {
			/*连接url*/
			URL url =  new URL("https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+access_token);
		    //J2SE的类型强制转换,把URL转换成它的一个子类.
			/*打开连接*/
			HttpURLConnection connection  = (HttpURLConnection)url.openConnection();
		    //GET方式,直接做的是读取
			/*得到输入流in*/
			 in = connection.getInputStream();
			/*in是字节流,把字节流转换为字符流*/
			/*得到InputStreamReader*/
			 reader = new InputStreamReader(in,"UTF-8");
			/*BufferedReader提高读取效率*/
			/*得到BufferedReader,breader比reader执行效率高,执行快*/
			 breader = new BufferedReader(reader);
			String str = null;
			while(null != (str=breader.readLine())){
				strb.append(str);
				
			}
			/*
			关闭breader*/
			breader.close();
			
			/*关闭reader*/
			reader.close();
			
			/*关闭in*/
			in.close();
		} //catch (MalformedURLException e) {
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
/*		
		关闭breader
		breader.close();
		
		关闭reader
		reader.close();
		
		关闭in
		in.close();*/
		return strb.toString();
	}
	/*
	 * create菜单
	 */
      //public static void createCaiDan() {
	  //public static void create(String access_token,List<CaiDan> caiDanList)  {//token,
	public static String create(String access_token,List<CaiDan> caiDanList)  {//token,
		/*连接对象*/  
		HttpURLConnection connection = null;
		  /*返回的字符串*/
		  StringBuffer strb =  new StringBuffer();
		  try {
			URL url = new URL("https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token);
			 connection= (HttpURLConnection)url.openConnection();
            
			 /*设置POST*/
			 connection.setDoOutput(true);//流往出写的方式是POST方式.默认是GET方式.
            connection.setRequestMethod("POST");
            
            /*得到输出流*/
            OutputStream  out  =  connection.getOutputStream();
            
            /*封装OutputStreamWriter*/
            OutputStreamWriter writer = new OutputStreamWriter(out);
            
            /*封装BufferedWriter*/
            BufferedWriter bwriter = new BufferedWriter(writer);
            
            //?????????????????????????????
            /*写出*/
            bwriter.write(getStr(caiDanList));
            
            /*flush*/
            bwriter.flush();
            
            /*得到输入流*/
            InputStream in = connection.getInputStream();
            /*封装InputSreamReader*/
            InputStreamReader reader =  new InputStreamReader(in);
            /*封装BufferedReader*/
            BufferedReader breader = new BufferedReader(reader);
            /*读取*/
            String str = null;
            
            while(null!=( str = breader.readLine())){
            	strb.append(str);
            }
            System.out.println(strb);
            /*关闭out*/
            out.close();
            /*关闭writer*/
            writer.close();
            /*关闭bwriter*/
            bwriter.close();
            /*关闭in*/
            in.close();
            /*关闭reader*/
            reader.close();
            /*关闭breader*/
            breader.close();
		  } //catch (MalformedURLException e) {
	   catch (Exception e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		}//
	    if(null!=connection){
	    	connection.disconnect();
	     }
		//return access_token;
	    return strb.toString();
      }
	/*
	 * 构建自定义菜单的报文
	 */
	public static String getStr(List<CaiDan> caiDanList){
		StringBuffer strb  =  new StringBuffer();
		strb.append("{");
		strb.append("\"button\":[");
		
/*		strb.append("  {   ");
		strb.append("  \"button\":[  ");
		strb.append("  {	  ");
		strb.append("  \"type\":\"click\",");
		strb.append("  \"name\":\"今日歌曲\",");
		strb.append("  \"key\":\"V1001_TODAY_MUSIC\"");
		strb.append("  },  ");
		strb.append("  {  ");
		strb.append("  \"name\":\"菜单\",");
		strb.append("  sub_button\":[");
		strb.append("   { ");
		strb.append("   \"type\":\"view\",");
		strb.append("    name\":\"搜索\",");
		strb.append("   \"url\":\"http://www.soso.com/\"");
		strb.append("   }, ");
		strb.append("     { ");
		strb.append("   \"type\":\"miniprogram\", ");
		strb.append("   \"name\":\"wxa\", ");
		strb.append("  \"url\":\"http://mp.weixin.qq.com\", ");
		strb.append("   \"appid\":\"wx286b93c14bbf93aa\",");
		strb.append("   \"pagepath\":\"pages/lunar/index.html\"");
		strb.append("     },");
		strb.append("    { ");
		strb.append("   \"type\":\"click\",");
		strb.append("   \"name\":\"赞一下我们\",");
		strb.append("   \"key\":\"V1001_GOOD\"");
		strb.append("    }]");
		strb.append("     }] ");
		strb.append("     }] ");
		strb.append("   }");*/
		CaiDan caiDan =  null;
		CaiDan caiDan_ =  null;
		for(int x=0 ; x < caiDanList.size();x++){
			caiDan =  caiDanList.get(x);
			if(null==caiDan.getSub_button()){
			   strb.append("{");
			   strb.append( " \"type\": \""+caiDan.getType()+"\", ");
               strb.append( "       \"name\": \""+caiDan.getName()+"\", ");
       		if(CaiDan.CLICK.equals(caiDan.getType())){
				strb.append("                \"key\": \""+caiDan.getKey()+"\" ");		
			}else if(CaiDan.VIEW.equals(caiDan.getType())){
				strb.append(" \"url\": \""+caiDan.getUrl()+"\" ");
			}   		
			strb.append("             }");
			}else{
			strb.append("    { ");
           strb.append(" \"name\":\""+caiDan.getName()+"\",");
           strb.append(" \"sub_button\":[ ");
           for(int xx=0;xx<caiDan.getSub_button().size();xx++){
        	   caiDan_ = caiDan.getSub_button().get(xx);
        	   strb.append("{");
			   strb.append( " \"type\": \""+caiDan_.getType()+"\", ");
               strb.append( "       \"name\": \""+caiDan_.getName()+"\", ");
       		if(CaiDan.CLICK.equals(caiDan_.getType())){
				strb.append("                \"key\": \""+caiDan_.getKey()+"\" ");		
			}else if(CaiDan.VIEW.equals(caiDan_.getType())){
				strb.append(" \"url\": \""+caiDan_.getUrl()+"\" ");
			}   		
			strb.append("             }");
			if(xx+1!=caiDan.getSub_button().size()){
				strb.append(",");
			}
           }
			strb.append("        ]       ");		
			strb.append("        }       ");		

			}

			if(x+1!=caiDanList.size()){
				strb.append(",");
			}
		}
		strb.append("]");
		strb.append("}");
		
		return strb.toString();
		
	}
	
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import base.token.AccessToken;
import bean.caidan.CaiDan;

import wx.util.WX_CaiDan;
import wx.util.WX_Token;


public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
/*          try {
			//WX_Token.getAccessTokenByNet();
			System.out.println(WX_Token.getAccessTokenByNet());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		   AccessToken accessToken = null;
		try {
	           accessToken = WX_Token.getAccessTokenByNet();
	           System.out.println(accessToken.getAccess_token());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
          //WX_CaiDan.create(accessToken.getAccess_token(), null);
          
          List<CaiDan> caiDanList = new ArrayList<CaiDan>();
          
          CaiDan caidan001 =  new  CaiDan();
          
          caidan001.setName("说明001");
          caidan001.setType(CaiDan.CLICK);
          caidan001.setKey("001");
          caiDanList.add(caidan001);
          
          CaiDan caidan002 =  new  CaiDan();
          caidan002.setName("说明002");
          caidan002.setType(CaiDan.VIEW);
          caidan002.setKey("002");
          caidan002.setUrl("http://www.baidu.com/");
          caiDanList.add(caidan002);
          
          /**
           * 构建带有下级菜单的
           * sub_caidan001是一级菜单
           */
          CaiDan sub_caidan001 =  new  CaiDan();
          sub_caidan001.setName("sub_caidan001");
          List<CaiDan> sub_buttonList  =  new  ArrayList<CaiDan>();
          sub_caidan001.setSub_button(sub_buttonList);
          /**
           * sub_caiDan001是sub_caidan001的下级菜单
           * name是下级001
           * type是click
           * key是sub001
           */
          CaiDan sub_caiDan001 =  new CaiDan();
          sub_caiDan001.setName("下级001");
          sub_caiDan001.setType(CaiDan.CLICK);
          sub_caiDan001.setKey("sub001");
          sub_buttonList.add(sub_caiDan001);
          /**
           * sub_caiDan002是sub_caidan001的下级菜单
           * name是下级002
           * type是click
           * key是sub002
           */
          CaiDan sub_caiDan002 =  new CaiDan();
          sub_caiDan002.setName("下级002");
          sub_caiDan002.setType(CaiDan.VIEW);
          sub_caiDan002.setUrl("http://www.baidu.com/");
          sub_buttonList.add(sub_caiDan002);

          caiDanList.add(sub_caidan001);

          WX_CaiDan.create(accessToken.getAccess_token(), caiDanList);
          
          /*create*/
          System.out.println(WX_CaiDan.create(accessToken.getAccess_token(), caiDanList));
          
          /*报文*/
          System.out.println(WX_CaiDan.getStr(caiDanList));
          
          //System.out.println(WX_CaiDan.query(accessToken.toString()));
          /*query*/
          System.out.println(WX_CaiDan.query(accessToken.getAccess_token()));
          /*delete*/
          System.out.println(WX_CaiDan.delete(accessToken.getAccess_token()));
	}

}

1231231

转载于:https://my.oschina.net/u/3206447/blog/911569

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值