微信&java 开发3 菜单接口

初始化菜单首先要获取accesstoken,关于accesstoken的获取和缓存在下面和后面的文章中介绍

public class WeixinTest {
	public static void main(String[] args) {
		try {
			AccessToken token = WeixinUtil.getAccessToken();
			System.out.println("票据"+token.getToken());
			System.out.println("有效时间"+token.getExpiresIn());
			String menu = JSONObject.fromObject(WeixinUtil.initMenu()).toString();
			int result = WeixinUtil.createMenu(token.getToken(), menu);
			if(0 == result) {
				System.out.println("成功!");
			} else {
				System.out.println("失败!");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

看一下WeiXinUtil.getAccessToken()

/**
	 * 获取accessToken
	 * 
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static AccessToken getAccessToken() throws ParseException,
			IOException {
		AccessToken token = new AccessToken();
		String url = ACCESS_TOKEN_URL.replace("APPID", WeiXinPropUtil.APPID).replace(
				"APPSECRET", WeiXinPropUtil.APPSECRET);
		JSONObject jsonObject = doGetStr(url);
		if (jsonObject != null) {
			token.setToken(jsonObject.getString("access_token"));
			token.setExpiresIn(jsonObject.getInt("expires_in"));
		}
		return token;
	}


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

这里  APPID APPSECRET我是存到properties中,然后读取 这样再有变化时只要修改properties文件即可

public class WeiXinPropUtil {
	public static String APPID = "";
	public static String APPSECRET = "";
	public static String WebDomain = "";
	
	private static Properties props = new Properties();
	private static InputStream in;

	static {
		try {
			in = WeixinUtil.class.getResourceAsStream("/properties/web.properties");
			props.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (!props.isEmpty()) {
			WebDomain = props.getProperty("webDomain").toString();
			APPID = props.getProperty("APPID").toString();
			APPSECRET = props.getProperty("APPSECRET").toString();
		}
	}
	
	private WeiXinPropUtil(){}
}


/**
	 * get请求
	 * 
	 * @param url
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static JSONObject doGetStr(String url) throws ParseException,
			IOException {

		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		JSONObject jsonObject = null;
		HttpResponse httpResponse = client.execute(httpGet);
		HttpEntity entity = httpResponse.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");
			jsonObject = JSONObject.fromObject(result);
		}
		return jsonObject;
	}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值