初始化菜单首先要获取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;
}
这里 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;
}