+发表新主题
查看: 1578|回复: 0

[代码片段] java版,微信公众平台新手入门第三节

[复制链接]

[代码片段] java版,微信公众平台新手入门第三节

[复制链接]
风的传说自由 发表于 2015-10-15 13:35:55 浏览:  1578 回复:  0 [显示全部楼层] 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
java版 微信公众平台开发


access_token 获取

微信自定义菜单

提交微信自定义菜单

查询微信自定义菜单

删除微信自定义菜单

access_token 获取
  1. /**
  2. * 公众平台通用接口工具类
  3. */
  4. public class WeixinUtil {
  5.    private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
  6.    
  7.    // 获取access_token的接口地址(GET) 限200(次/天)
  8.    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
  9.    /**
  10.     * 获取access_token
  11.     * @param appid 凭证
  12.     * @param appsecret 密钥
  13.     * @return
  14.     */
  15.    public static AccessToken getAccessToken(String appid, Stringappsecret) {
  16.       AccessToken accessToken = null;
  17.       String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
  18.       JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
  19.       // 如果请求成功
  20.       if (null != jsonObject) {
  21.         try {
  22.            accessToken = new AccessToken();
  23.            accessToken.setToken(jsonObject.getString("access_token"));
  24.            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
  25.         } catch (JSONException e) {
  26.            accessToken = null;
  27.            // 获取token失败
  28.            log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
  29.         }
  30.       }
  31.       return accessToken;
  32.    }
  33.    /**
  34.     * 发起https请求并获取结果
  35.     * @param requestUrl 请求地址
  36.     * @param requestMethod 请求方式(GET、POST)
  37.     * @param outputStr 提交的数据
  38.     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
  39.     */
  40.    public static JSONObject httpRequest(String requestUrl, StringrequestMethod, String outputStr) {
  41.       JSONObject jsonObject = null;
  42.       StringBuffer buffer = new StringBuffer();
  43.       try {
  44.         // 创建SSLContext对象,并使用我们指定的信任管理器初始化
  45.         TrustManager[] tm = { new MyX509TrustManager() };
  46.         SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  47.         sslContext.init(null, tm, new java.security.SecureRandom());
  48.         // 从上述SSLContext对象中得到SSLSocketFactory对象
  49.         SSLSocketFactory ssf = sslContext.getSocketFactory();
  50.         URL url = new URL(requestUrl);
  51.         HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
  52.         httpUrlConn.setSSLSocketFactory(ssf);
  53.         httpUrlConn.setDoOutput(true);
  54.         httpUrlConn.setDoInput(true);
  55.         httpUrlConn.setUseCaches(false);
  56.         // 设置请求方式(GET/POST)
  57.         httpUrlConn.setRequestMethod(requestMethod);
  58.         if ("GET".equalsIgnoreCase(requestMethod))
  59.            httpUrlConn.connect();
  60.         // 当有数据需要提交时
  61.         if (null != outputStr) {
  62.            OutputStream outputStream = httpUrlConn.getOutputStream();
  63.            // 注意编码格式,防止中文乱码
  64.            outputStream.write(outputStr.getBytes("UTF-8"));
  65.            outputStream.close();
  66.         }
  67.         // 将返回的输入流转换成字符串
  68.         InputStream inputStream = httpUrlConn.getInputStream();
  69.         InputStreamReader inputStreamReader = newInputStreamReader(inputStream, "utf-8");
  70.         BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  71.         String str = null;
  72.         while ((str = bufferedReader.readLine()) != null) {
  73.            buffer.append(str);
  74.         }
  75.         bufferedReader.close();
  76.         inputStreamReader.close();
  77.         // 释放资源
  78.         inputStream.close();
  79.         inputStream = null;
  80.         httpUrlConn.disconnect();
  81.         jsonObject = JSONObject.fromObject(buffer.toString());
  82.       } catch (ConnectException ce) {
  83.         log.error("Weixinserver connection timed out.");
  84.       } catch (Exception e) {
  85.         log.error("httpsrequest error:{}", e);
  86.       }
  87.       return jsonObject;
  88.    }
  89. }
  90.    
  91.    /**
  92.     * 创建菜单
  93.     */
  94.    public static String createMenu(String params, String accessToken) throws Exception {
  95.       HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);
  96.       httpost.setEntity(new StringEntity(params, "UTF-8"));
  97.       HttpResponse response = httpclient.execute(httpost);
  98.       String jsonStr = EntityUtils.toString(response.getEntity(),"utf-8");
  99.       JSONObject object = JSON.parseObject(jsonStr);
  100.       return object.getString("errcode");
  101.    }
  102.    
  103.    /**
  104.     * 查询菜单
  105.     */
  106.    public static String getMenuInfo(String accessToken) throws Exception {
  107.       HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);
  108.       HttpResponse response = httpclient.execute(get);
  109.       String jsonStr = EntityUtils.toString(response.getEntity(),"utf-8");
  110.       return jsonStr;
  111.    }
  112.    
  113.    /**
  114.     * 删除自定义菜单
  115.     */
  116.    public static String getAccessToken(String accessToken) throws Exception {
  117.       HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);
  118.       HttpResponse response = httpclient.execute(get);
  119.       String jsonStr = EntityUtils.toString(response.getEntity(),"utf-8");
  120.       JSONObject object = JSON.parseObject(jsonStr);
  121.       return object.getString("errcode");
  122.    }
复制代码


回复

使用道具 举报


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版| 赣南网

© 2013-2016 Comsenz Inc. Powered by Discuz! X3.4

用微信扫一扫

赣南网