微信公众平台自定义菜单创建 -JAVA

原创
2013/09/13 22:48
阅读数 1.2W

微信公众平台开发之自定义菜单创建JAVA源码

创建项目添加httpclient.jar、fastjson.jar支持

 

 

自定义菜单的问题总结:

1.自定义菜单只有服务号可以申请,订阅号暂时无法申请(继续观望微信的开放政策)

2.菜单响应回复方式可以是【图文】、【音乐】、【文本】三种方式

3.自定义菜单创建之后无法立即生效,可以采用先取消关注,再关注的方式查看效果

 

 

微信自定义菜单创建官网文档

 

package com.using.weixin.common.https;  
      
    import org.apache.http.client.HttpClient;  
    import org.apache.http.client.methods.HttpGet;  
    import org.apache.http.client.methods.HttpPost;  
    import org.apache.http.conn.ClientConnectionManager;  
    import org.apache.http.conn.scheme.Scheme;  
    import org.apache.http.conn.scheme.SchemeRegistry;  
    import org.apache.http.impl.client.DefaultHttpClient;  
      
    public class HttpClientConnectionManager {  
          
          
        /** 
         * 获取SSL验证的HttpClient 
         * @param httpClient 
         * @return 
         */  
        public static HttpClient getSSLInstance(HttpClient httpClient){  
            ClientConnectionManager ccm = httpClient.getConnectionManager();  
            SchemeRegistry sr = ccm.getSchemeRegistry();  
            sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));  
            httpClient =  new DefaultHttpClient(ccm, httpClient.getParams());  
            return httpClient;  
        }  
          
        /** 
         * 模拟浏览器post提交 
         *  
         * @param url 
         * @return 
         */  
        public static HttpPost getPostMethod(String url) {  
            HttpPost pmethod = new HttpPost(url); // 设置响应头信息  
            pmethod.addHeader("Connection", "keep-alive");  
            pmethod.addHeader("Accept", "*/*");  
            pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");  
            pmethod.addHeader("Host", "mp.weixin.qq.com");  
            pmethod.addHeader("X-Requested-With", "XMLHttpRequest");  
            pmethod.addHeader("Cache-Control", "max-age=0");  
            pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");  
            return pmethod;  
        }  
      
        /**  
         * 模拟浏览器GET提交  
         * @param url  
         * @return  
         */  
        public static HttpGet getGetMethod(String url) {  
            HttpGet pmethod = new HttpGet(url);  
            // 设置响应头信息  
            pmethod.addHeader("Connection", "keep-alive");  
            pmethod.addHeader("Cache-Control", "max-age=0");  
            pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");  
            pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");  
            return pmethod;  
        }  
    }
package com.using.weixin.common.https;  
      
    import java.security.KeyManagementException;  
    import java.security.NoSuchAlgorithmException;  
      
    import javax.net.ssl.SSLContext;  
    import javax.net.ssl.TrustManager;  
      
    import org.apache.http.conn.ssl.SSLSocketFactory;  
      
    public class MySSLSocketFactory extends SSLSocketFactory{  
          
        static{  
            mySSLSocketFactory = new MySSLSocketFactory(createSContext());  
        }  
          
        private static MySSLSocketFactory mySSLSocketFactory = null;  
          
          
          
        private static SSLContext createSContext(){  
            SSLContext sslcontext = null;  
            try {  
                sslcontext = SSLContext.getInstance("SSL");  
            } catch (NoSuchAlgorithmException e) {  
                e.printStackTrace();  
            }  
            try {  
                sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null);  
            } catch (KeyManagementException e) {  
                e.printStackTrace();  
                return null;  
            }  
            return sslcontext;  
        }  
          
        private MySSLSocketFactory(SSLContext sslContext) {  
            super(sslContext);  
            this.setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER);  
        }  
          
        public static MySSLSocketFactory getInstance(){  
            if(mySSLSocketFactory != null){  
                return mySSLSocketFactory;  
            }else{  
                return mySSLSocketFactory = new MySSLSocketFactory(createSContext());  
            }  
        }  
          
    }
package com.using.weixin.common.https;  
      
    import java.security.cert.CertificateException;  
    import java.security.cert.X509Certificate;  
      
    import javax.net.ssl.X509TrustManager;  
      
    /** 
     *  
     * @author Administrator 
     * 
     */  
    public class TrustAnyTrustManager implements X509TrustManager{  
      
        @Override  
        public void checkClientTrusted(X509Certificate[] chain, String authType)  
                throws CertificateException {  
              
        }  
      
        @Override  
        public void checkServerTrusted(X509Certificate[] chain, String authType)  
                throws CertificateException {  
              
        }  
      
        @Override  
        public X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
      
    }
package com.using.weixin.common;  
      
    import org.apache.http.HttpResponse;  
    import org.apache.http.client.methods.HttpGet;  
    import org.apache.http.client.methods.HttpPost;  
    import org.apache.http.entity.StringEntity;  
    import org.apache.http.impl.client.DefaultHttpClient;  
    import org.apache.http.util.EntityUtils;  
      
    import com.alibaba.fastjson.JSON;  
    import com.alibaba.fastjson.JSONObject;  
    import com.using.weixin.common.https.HttpClientConnectionManager;  
      
    /** 
     * 微信自定义菜单创建 
     */  
    public class WxMenuUtils {  
        // http客户端  
        public static DefaultHttpClient httpclient;  
          
        static {  
            httpclient = new DefaultHttpClient();  
            httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端  
        }  
      
        public static void main(String[] args) {  
            try {  
                // 获取accessToken -参数appid,secret  
                String accessToken = getAccessToken("appid", "secret");  
                System.out.println(accessToken);  
                // 创建菜单  
                //String s = "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\":\"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查询\",\"key\":\"m_bus\"}]},{\"type\":\"click\",\"name\":\"关于企特\",\"key\":\"m_about\"}]}";  
                String s = "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\":\"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查询\",\"key\":\"m_bus\"},{\"type\":\"click\",\"name\":\"功能菜单\",\"key\":\"m_sysmenu\"}]},{\"name\":\"消息示例\",\"sub_button\":[{\"type\":\"click\",\"name\":\"关于企特\",\"key\":\"m_about\"},{\"type\":\"click\",\"name\":\"图文消息\",\"key\":\"m_imgmsg\"},{\"type\":\"click\",\"name\":\"音乐消息\",\"key\":\"m_musicmsg\"}]}]}";  
                String res = createMenu(s, accessToken);  
                System.out.println(res);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
          
          
        /** 
         * 创建菜单 
         */  
        public static String createMenu(String params, String accessToken) throws Exception {  
            HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);  
            httpost.setEntity(new StringEntity(params, "UTF-8"));  
            HttpResponse response = httpclient.execute(httpost);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            System.out.println(jsonStr);  
            JSONObject object = JSON.parseObject(jsonStr);  
            return object.getString("errmsg");  
        }  
      
        /** 
         * 获取accessToken 
         */  
        public static String getAccessToken(String appid, String secret) throws Exception {  
            HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);  
            HttpResponse response = httpclient.execute(get);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            JSONObject object = JSON.parseObject(jsonStr);  
            return object.getString("access_token");  
        }  
          
        /** 
         * 查询菜单 
         */  
        public static String getMenuInfo(String accessToken) throws Exception {  
            HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);  
            HttpResponse response = httpclient.execute(get);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            return jsonStr;  
        }  
          
        /** 
         * 删除自定义菜单 
         */  
        public static String deleteMenu(String accessToken) throws Exception {  
            HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);  
            HttpResponse response = httpclient.execute(get);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            JSONObject object = JSON.parseObject(jsonStr);  
            return object.getString("errmsg");  
        }  
    }

 

 

展开阅读全文
加载中

作者的其它热门文章

打赏
3
12 收藏
分享
打赏
2 评论
12 收藏
3
分享
返回顶部
顶部