您的位置:首页 > 移动开发 > 微信开发

微信公众平台开发学习记录(2)————自定义菜单创建

2016-03-02 20:55 573 查看
公众号调用各接口时都需使用access_token,access_token是公众号的全局唯一票据,获取access_token接口的调用频率限制为2000次/天,如果每次发送客服消息、获取用户信息、群发消息之前都要先调用获取access_token接口得到接口访问凭证,这显然是不合理的,一方面会更耗时(多了一次接口调用操作),另一方面2000次/天的调用限制恐怕也不够用。因此,在实际应用中,我们需要将获取到的access_token存储起来,然后定期调用access_token接口更新它,以保证随时取出的access_token都是有效的。

public static void main(String[] args) throws Exception {

// 获取access token
String str = "";
str = HttpUtil.http("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=****&secret=******");
System.out.println(str);

// 获取微信服务器IP地址
// 如果公众号基于消息接收安全上的考虑,需要获知微信服务器的IP地址列表,以便识别出哪些消息是微信官方推送给你的,哪些消息可能是他人伪造的,可以通过该接口获得微信服务器IP地址列表。
String str2 = HttpUtil
.http("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=<span style="font-family: Arial, Helvetica, sans-serif;">access_token</span>");
System.out.println(str2);
}
自定义菜单创建、删除、查询、查询配置接口如下:

public static void main(String[] args) throws Exception {

// 自定义菜单删除接口
String str5 = HttpUtil
.http("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=drnjhjklW1xANamBWNni5YrioFpgKrmok713WqRA3Ps9711fj5haRTUTLLAqbHZFmq7RooJoefzzDL1CdmSKBGeC7Qav_PKzwwaIRjHBxTMSkaKSxOQm8v6uaUZOspv5RVBiAAAWAG");
System.out.println(str5);

// 自定义菜单创建接口
String menuStr = "{\"button\":[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"},"
+ "{\"name\":\"菜单\", \"sub_button\":[{	\"type\":\"view\", \"name\":\"搜索\", \"url\":\"http://www.soso.com/\"},{\"type\":\"location_select\", \"name\":\"发送位置\",\"key\":\"rselfmenu_2_0\"},{\"type\":\"click\", \"name\":\"赞一下我们\",\"key\":\"V1001_GOOD\"}]},"
+ " { \"name\": \"扫码\",\"sub_button\": [{\"type\": \"scancode_waitmsg\",\"name\": \"扫码带提示\",\"key\": \"rselfmenu_0_0\", \"sub_button\": [] }, {\"type\": \"scancode_push\", \"name\": \"扫码推事件\", \"key\": \"rselfmenu_0_1\",\"sub_button\": []} ] }]}";
String str3 = HttpUtil
.httpsPostMethod(
"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=drnjhjklW1xANamBWNni5YrioFpgKrmok713WqRA3Ps9711fj5haRTUTLLAqbHZFmq7RooJoefzzDL1CdmSKBGeC7Qav_PKzwwaIRjHBxTMSkaKSxOQm8v6uaUZOspv5RVBiAAAWAG",
menuStr);
System.out.println(str3);

// 自定义菜单查询接口
String str4 = HttpUtil
.http("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=drnjhjklW1xANamBWNni5YrioFpgKrmok713WqRA3Ps9711fj5haRTUTLLAqbHZFmq7RooJoefzzDL1CdmSKBGeC7Qav_PKzwwaIRjHBxTMSkaKSxOQm8v6uaUZOspv5RVBiAAAWAG");
System.out.println(str4);

// 获取自定义菜单配置接口
String str6 = HttpUtil
.http("https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=drnjhjklW1xANamBWNni5YrioFpgKrmok713WqRA3Ps9711fj5haRTUTLLAqbHZFmq7RooJoefzzDL1CdmSKBGeC7Qav_PKzwwaIRjHBxTMSkaKSxOQm8v6uaUZOspv5RVBiAAAWAG");
System.out.println(str6);

}


HttpUtil:

package com.qs.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

public class HttpUtil {

public static String http(String url) throws Exception {
URL u = null;
HttpURLConnection con = null;
// 构建请求参数
StringBuffer sb = new StringBuffer();
// 尝试发送请求
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; text/html; charset=utf-8");
OutputStreamWriter osw = new OutputStreamWriter(con
.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
throw e;
} finally {
if (con != null) {
con.disconnect();
}
}
// 读取返回内容
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
}
} catch (Exception e) {
throw e;
}
return buffer.toString();
}

/**
* Https POST
*
* @throws
**/
public static String httpsPostMethod(String postURL, String postData) {
OutputStreamWriter out = null;
HttpsURLConnection conn = null;
InputStream is = null;
StringBuffer buffer = new StringBuffer();
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
// 更换服务如何获取凭证
URL console = new URL(postURL);
conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);

out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
out.write(postData);
out.flush();
conn.connect();

// 读取返回内容
is = conn.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
out.close();
is.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer.toString();
}

// https证书验证
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}

private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: