注意本文推送菜单示例未对异常做处理直接抛出,实际生产过程是不允许的。
public class CreateMenu {
public static void main(String[] args) throws Exception {
//微信菜单推送地址
String custmMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
//获取access_token
String accessToken = getAccessToken();
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(getMenuStr().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 menu = new JSONObject();//一级菜单对象
JSONArray list = new JSONArray();//一级菜单列表
//一级菜单内容(一级菜单最多允许3)
JSONObject subButton = new JSONObject();
JSONObject subButton2 = new JSONObject();
JSONObject subButton3 = new JSONObject();
//一级菜单内容2的二级菜单列表
JSONArray subList = new JSONArray();
JSONArray subList2 = new JSONArray();
JSONArray subList3 = new JSONArray();
//一级菜单内容2的二级菜单内容2
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
jsonObject.put("type", "view");
jsonObject.put("name", "百度");
jsonObject.put("url", "http://www.baidu.com/");
subList.put(jsonObject);
jsonObject2.put("type", "view");
jsonObject2.put("name", "内涵段子");
jsonObject2.put("url", "http://www.budejie.com/");
subList2.put(jsonObject2);
jsonObject3.put("type", "view");
jsonObject3.put("name", "新闻纵览");
jsonObject3.put("url", "http://news.baidu.com/");
subList3.put(jsonObject3);
subButton.put("name", "度娘");
subButton.put("sub_button", subList);
subButton2.put("name", "未完待续");
subButton2.put("sub_button", subList2);
subButton3.put("name", "敬请期待");
subButton3.put("sub_button", subList3);
list.put(subButton);
list.put(subButton2);
list.put(subButton3);
menu.put("button", list);
return menu.toString();
}
public static String getAccessToken() throws Exception{
//获取accss_token的地址
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appId&secret=你的appsecret";
URL url = new URL(accessTokenUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
//获取返回的字符
InputStream inputStream = connection.getInputStream();
int size =inputStream.available();
byte[] bs =new byte[size];
inputStream.read(bs);
String message=new String(bs,"UTF-8");
//获取access_token
JSONObject jsonObject = new JSONObject(message);
return jsonObject.getString("access_token");
}