公衆號調用各接口時都需使用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;
}
}
}