// 凭证获取(GET) token 接口
private static final String TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
// 获取token接口
public static String getTokenUrl(String appId, String appSecret) {
return String.format(TOKEN, appId, appSecret);
}
//获取微信 AccessToken
public static AccessToken getAccessToken(String appId, String appSecret) {
AccessToken token = null;
String tockenUrl = WxApi.getTokenUrl(appId, appSecret);
JSONObject jsonObject = httpsRequest(tockenUrl, HttpMethod.GET, null);
if (null != jsonObject) {
if(jsonObject.containsKey("errcode")){
int errorCode = jsonObject.getInteger("errcode");
String errorMsg = jsonObject.getString("errmsg");
if(errorCode==0){
//存在 且为0 微信18年后模式
String access_token= jsonObject.getString("access_token");
Integer expires_in= jsonObject.getInteger("expires_in");
}
}else{
//不存在时 微信18年以前模式
String access_token= jsonObject.getString("access_token");
Integer expires_in= jsonObject.getInteger("expires_in");
}
}
return token;
}
/**
* @Title: httpsRequest
* @Description: 发送https请求
* @param requestUrl 请求地址
* @param requestMethod 请求方法
* @param outputStr
* @return
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL");//jdk7 默认 使用 TLS1模式 jdk8下默认 TLSv1.2模式 需求强制转换
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
//outSSLSocket(ssf);
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSON.parseObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}