1、自定义菜单最多包括3个一级菜单,每个一级菜单最多包含5个二级菜单。
2、一级菜单最多4个汉字,二级菜单最多7个汉字,多出来的部分将会以“…”代替。
3、创建自定义菜单后,菜单的刷新策略是,在用户进入公众号会话页或公众号profile页时,如果发现上一次拉取菜单的请求在5分钟以前,就会拉取一下菜单,如果菜单有更新,就会刷新客户端的菜单。测试时可以尝试取消关注公众账号后再次关注,则可以看到创建后的效果。
直接上代码,这里提供一个工具类。
MenuUtil类:
import com.lonbon.model.menu.*;
import net.sf.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MenuUtil {
/**
* 创建自定义菜单(每天限制1000次)
* *
Menu menu = getMenu();
//把菜单转换成json格式
String jsonMenu = JSONObject.fromObject(menu).toString();
System.out.println("jsonMenu: " + jsonMenu);
int status = 0;
//调用微信的创建菜单接口,主要是获取到access_token, post请求
String path = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="
+ GetTokenUtil.getAccessToken().getToken();
try {
URL url = new URL(path);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.connect();
OutputStream os = http.getOutputStream();
//发送请求
os.write(jsonMenu.getBytes("UTF-8"));
os.close();
//接收响应
InputStream is = http.getInputStream();
int size = is.available();
byte[] bt = new byte[size];
is.read(bt);
String message = new String(bt,"UTF-8");
JSONObject jsonMsg = JSONObject.fromObject(message);
//得到返回码的值
status = Integer.parseInt(jsonMsg.getString("errcode"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return status;
}
/**
* 封装菜单数据
* */
public static Menu getMenu(){
ComplexButton cx_1 = new ComplexButton();
//菜单名称
cx_1.setName("考勤打卡");
//菜单的响应动作类型。view表示网页类型,click表示点击类型,miniprogram表示小程序类型
cx_1.setType("view");
//网页对应的路径。用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的网页URL,
//可与网页授权获取用户基本信息接口结合,获得用户基本信息
cx_1.setUrl("http://lonbon.natapp4.cc/wxLogin");
ComplexButton cx_2 = new ComplexButton();
cx_2.setName("考勤记录");
cx_2.setType("view");
cx_2.setUrl("http://lonbon.natapp4.cc/recordServlet");
Menu menu = new Menu();
menu.setButton(new ComplexButton[]{cx_1,cx_2});
return menu;
}
}
实体类ComplexButton:
public class ComplexButton {
private String name; //菜单名称
private String type; //菜单类型
private String key; //key值
private String url;
private Button[] sub_button; //子级菜单
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Button[] getSub_button(){
return sub_button;
}
public void setSub_button(Button[] sub_button) {
this.sub_button = sub_button;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
实体类Menu :
public class Menu {
private ComplexButton[] button;
public ComplexButton[] getButton() {
return button;
}
public void setButton(ComplexButton[] button) {
this.button = button;
}
}