java微信自定義菜單(java微信開發學習筆記5)(完)(整個項目的源代碼在最後)

我的微信公衆號是個人訂閱號,個人訂閱號不能認證,所以沒有自定義菜單的權限。我使用的是微信公衆平臺提供的一個測試賬號。
測試賬號
測試號裏面會提供一個appid和appsecret,同樣需要接口配置。
配置接口

創建菜單:

package com.weixin.util;
import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.weixin.menu.Button;
import com.weixin.menu.ClickButton;
import com.weixin.menu.Menu;
import com.weixin.menu.ViewButton;

import net.sf.json.JSONObject;

public class HttpUtil {
    private static final String APPID = "APPID";
    private static final String APPSECRET = "APPSECRET";


    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    /**
     * get請求
     * @param url
     * @return
     */
    public static JSONObject doGetStr(String url) throws ParseException, IOException{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.fromObject(result);
            }
        return jsonObject;
    }

    /**
     * post請求
     * @param url
     * @param outStr
     * @return
     */
    public static JSONObject doPostStr(String url,String outStr){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonObject = null;
        httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            jsonObject = JSONObject.fromObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 通過判斷獲取AccessToken:本地-網絡
     * @return
     * @throws IOException
     */
    public static String getAccessToken() throws IOException{
        String filePath = "E:/zx/access_token/access_token01.txt";
        String access_token = null;
        String read= ReadAndWriteTxt.readFile(filePath);
        if (read.equals("001")) {
            access_token = getAccessTokenHttp();
            String str = access_token+"++"+ReadAndWriteTxt.getTime;
            ReadAndWriteTxt.writeFile(filePath, str);
            System.out.println("new");
        }else if((ReadAndWriteTxt.getTime - Integer.valueOf(read.split("++")[1]).intValue()) > 7200){
            access_token = getAccessTokenHttp();
            String str = access_token+"++"+ReadAndWriteTxt.getTime;
            ReadAndWriteTxt.writeFile(filePath, str);
            System.out.println("update");
        }else {
            access_token = read.split("++")[0];
            System.out.println("show");
        }
        return access_token;
    }

    /**
     * 獲取微信的AccessToken
     * @return
     * @throws ParseException
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static String getAccessTokenHttp() throws ParseException, IOException{
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        JSONObject jsonObject = doGetStr(url);
        Map<String, String> maps = null;
        if (jsonObject != null) {
            maps = (Map<String, String>) JSON.parse(jsonObject.toString());
        }
        String access_token = maps.get("access_token");
        return access_token;
    }

    /**
     * 初始化菜單
     * @return
     */
    public static Menu initMenu(){
        Menu menu = new Menu();
        ClickButton button11 = new ClickButton();
        button11.setName("click菜單");
        button11.setType("click");
        button11.setKey("11");

        ViewButton button21 = new ViewButton();
        button21.setName("view菜單");
        button21.setType("view");
        button21.setUrl("https://www.baidu.com/");

        ClickButton button31 = new ClickButton();
        button31.setName("掃碼事件");
        button31.setType("scancode_push");
        button31.setKey("31");

        ClickButton button32 = new ClickButton();
        button32.setName("地理位置");
        button32.setType("location_select");
        button32.setKey("32");

        Button button = new Button();
        button.setName("菜單");
        button.setSub_button(new Button[]{button31,button32});

        menu.setButton(new Button[]{button11,button21,button});

        return menu;
    }

    public static int creatMenu(String token,String menu){
        int result = 0;
        String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = doPostStr(url, menu);
        if (jsonObject != null) {
            result = jsonObject.getInt("errcode");
        }
        return result;
    }
}

寫一個測試類

package com.weixin.text;

import java.io.IOException;


import com.weixin.util.HttpUtil;

import net.sf.json.JSONObject;

public class Test {

    public static void main(String[] args) throws IOException{
        String menu = JSONObject.fromObject(HttpUtil.initMenu()).toString();
        int result = HttpUtil.creatMenu(HttpUtil.getAccessToken(), menu);
        if (result == 0) {
            System.out.println("創建菜單成功");
        }else {
            System.out.println("錯誤碼:"+result);
        }
    }

}

源碼:
http://download.csdn.net/download/zxxz5201314/9933934
PS:終於審覈過了。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章