微信公众号开发(三)
自定义菜单开发
根据微信自定义菜单文档,创建、删除自定义菜单只要向微信post一个请求就可以了
创建自定义菜单
请求的url: https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
请求参数(json格式):
{
"button":[
{
"type":"click",
"name":"今日歌曲",
"key":"feng_01"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.baidu.com/"
},
{
"type":"view",
"name":"视频",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"赞一下我",
"key":"feng_02"
}]
}]
}
这串json我是放在一个txt文件里,直接读取的。
发起请求:
public static void createWxMenu() {
try {
File file = new File("C:/Users/feng/Desktop/1.txt");
if (file.isFile() && file.exists()) {
FileInputStream in = new FileInputStream(file);
//微信只接受UTF-8的格式
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer sb = new StringBuffer();
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
sb.append(lineTxt);
}
in.close();
br.close();
NetUtil.httpPost(action, sb.toString());
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
http方法
public static String httpPost(String reqUrl, String reqData){
HttpURLConnection conn = null;
OutputStream os = null;
try {
conn = (HttpURLConnection) new URL(reqUrl).openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setReadTimeout(15*1000);
conn.setConnectTimeout(5*1000);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = conn.getOutputStream();
os.write(reqData.getBytes("UTF-8"));
System.out.println("req:"+reqData);
int responseCode = conn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
String resptxt = toString(conn.getInputStream());
System.out.println(resptxt);
return resptxt;
}else{
System.out.println("连接失败");
}
}catch(Exception e){
System.out.println("连接异常:"+e.getMessage());
e.printStackTrace();
}finally{
if (os != null)
try {
os.close();
} catch (Exception e) {
}
if (conn != null)
conn.disconnect();
}
return null;
}
调用结果:
查看微信, 没有问题
而菜单的详细设置请查看微信的文档,更改json就可以了,还有注意的一点就是这里的创建是以替换的形式执行的,它会把之前的菜单都去掉后再创建。
删除自定义菜单
请求url: https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN
http请求方式:GET
直接发起请求就可以了