微信公众平台开发之个性菜单创建

1.先创建一个properties文件保存appid和appsecret

import java.io.IOException;
import java.util.Properties;
//根据我创建的weixin.properties文件获取appid和appsecret
public class WxConfig {
    private static Properties p = null;

    public static String getWxProperty(String key) {
        if (p == null) {
            p = new Properties();
            try {
                p.load(WxConfig.class.getClassLoader().getResourceAsStream(
                        "weixin.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return p.getProperty(key);
    }
}

获取文件夹内的appid和appsecret

2.根据appid和appsecret获取access_token

public static String getAccessToken() {
        synchronized (accessToken) {
            long ex = (System.currentTimeMillis() - createTime) / 1000;
            if (StringUtils.isBlank(accessToken) || ex >= 7000) {
                // 刷新
                StringBuffer url = new StringBuffer();
                url.append("https://api.weixin.qq.com/cgi-bin/token?");
                url.append("grant_type=client_credential");
                url.append("&appid=" + WxConfig.getWxProperty("appid"));
                url.append("&secret=" + WxConfig.getWxProperty("appsecret"));

                BufferedReader in = null;

                String content = null;
                try {
                    // 定义HttpClient
                    HttpClient client = new DefaultHttpClient();
                    // 实例化HTTP方法
                    HttpGet get = new HttpGet();
                    get.setURI(new URI(url.toString()));
                    HttpResponse res = client.execute(get);

                    in = new BufferedReader(new InputStreamReader(res
                            .getEntity().getContent()));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    in.close();
                    content = sb.toString();
                } catch (Exception e) {
                } finally {
                    if (in != null) {
                        try {
                            in.close();// 最后要关闭BufferedReader
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                if (content != null) {
                    JSONObject json = JSONObject.fromObject(content);
                    accessToken = json.getString("access_token");
                    createTime = System.currentTimeMillis();
                }
            }
            // System.out.println("accessToken——" + accessToken);
            return accessToken;
        }
    }

3.创建初始化webapp自动创建菜单监听器

package com.msweixin.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CreateMenus implements ServletContextListener {

    private static final String menus1 = "{\"button\":["
            + "{\"type\":\"view\",\"name\":\"百度1\",\"url\":\"http://www.baidu.com\"},"
            + "{\"type\":\"view\",\"name\":\"腾讯1\",\"url\":\"http://www.qq.com\"},"
            + "{\"name\":\"更多\",\"sub_button\":["
            + "{\"type\":\"view\",\"name\":\"1\",\"url\":\"http://www.taobao.com\"}]"
            + "}]," + "\"matchrule\":" + "{\"sex\":\"1\"}}";
    private static final String menus2 = "{\"button\":["
            + "{\"type\":\"view\",\"name\":\"百度2\",\"url\":\"http://www.baidu.com\"},"
            + "{\"type\":\"view\",\"name\":\"腾讯2\",\"url\":\"http://www.qq.com\"},"
            + "{\"name\":\"更多\",\"sub_button\":["
            + "{\"type\":\"view\",\"name\":\"2\",\"url\":\"http://www.taobao.com\"}]"
            + "}]," + "\"matchrule\":" + "{\"sex\":\"2\"}}";
    public void contextDestroyed(ServletContextEvent event) {

    }

    public void contextInitialized(ServletContextEvent event) {
        System.out.println(CreateMenus.menus1);
        try {
            String createReturn = createMenusOfWechat(CreateMenus.menus1);
            event.getServletContext().log(
                    "---create menu1 was " + createReturn + "---");

            String createReturn2 = createMenusOfWechat(CreateMenus.menus2);
            event.getServletContext().log(
                    "---create menu2 was " + createReturn2 + "---");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @throws IOException
     *             创建Menu
     * 
     * @Title: createMenu
     * @Description: 创建Menu
     * @param @throws IOException 设定文件
     * @return int 返回类型
     * @throws
     */
    public static String createMenusOfWechat(String menu) throws IOException {
        // 获得access_token
        String access_token = WxUtils.getAccessToken();
        String action = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token="
                + access_token;
        try {
            URL url = new URL(action);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            OutputStream os = http.getOutputStream();
            os.write(menu.getBytes("UTF-8"));
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            return "返回信息" + message;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "createMenu 失败";
    }

}

 

posted @ 2016-09-30 17:03  GeniusFirstMove  阅读(271)  评论(0编辑  收藏  举报