微信开发的时候自定义菜单
使用java代码开发自定义菜单
第一步,获取到accessToken(接口的accessToken和网络授权的accesstoken不一样)
可以查看我的另一篇博客
第二部组装数据
直接上代码
public static void createCustomMenu(String accesstoken,String menu) throws Exception{
String custmMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
custmMenuUrl = custmMenuUrl + accesstoken;
URL url = new URL(custmMenuUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
OutputStream outputStream = connection.getOutputStream();
outputStream.write(menu.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
int size =inputStream.available();
byte[] bs =new byte[size];
inputStream.read(bs);
String message=new String(bs,"UTF-8");
System.out.println(message);
}
组装数据
public static String getMenuStr() throws JSONException,Exception{
JSONObject firstLevelMenu = new JSONObject();//一级菜单
JSONArray firstLevelMenuArray = new JSONArray();//一级菜单列表
//一级菜单内容3
JSONObject firstLevelMenuContext3 = new JSONObject();
firstLevelMenuContext3.put("type", "view");
firstLevelMenuContext3.put("name", "无极");
//当我们给菜单设置一个按钮的时候,在这个按钮下面设置就一个事件,这样你在点击这个按钮的时候就会触发这个事件,比如说你就可以跳转到你服务器上的页面,这样就可以进行开发了,你也可以在这个按钮下面跳转到控制器,在这个控制器里面获去用户的信息什么的
String qq= "http://15326b0d65.iok.la/org.zsl.hnust/user/bulidWeiXinInter";
qq = java.net.URLEncoder.encode(qq, "UTF-8");
firstLevelMenuContext3.put("url", "http://open.weixin.qq.com/connect/oauth2/authorize?appid=wx68d51b01803f7838&redirect_uri="+qq+"&response_type=code&scope=snsapi_userinfo&state=[state]#wechat_redirect");
firstLevelMenuArray.add(firstLevelMenuContext3);
firstLevelMenu.put("button", firstLevelMenuArray);
return firstLevelMenu.toString();
}
最后是调用这个方法
WeiXinUtil weiXinUtil = new WeiXinUtil();
//与微信建立链接获取token
Map<String,Object>map=weiXinUtil.getAccessToken();
//建造菜单
//(String)map.get("access_token")获取token
//组装菜单weiXinUtil.getMenuStr()
weiXinUtil.createCustomMenu((String)weiXinUtil.getAccessToken().get("access_token"), weiXinUtil.getMenuStr());