微信公众平台开发使用Java怎么实现获取token
更新时间:2023-09-121. 前言
在微信公众平台开发中,获取access_token是非常重要的一步,因为它是进行微信API调用的凭证。access_token必须通过接口获取,每个access_token的有效期是7200秒,过期需要重新获取。
本文将介绍如何使用Java语言实现获取微信公众平台的access_token。
2. 获取access_token
在Java中获取微信公众平台的access_token,我们可以使用HttpClient发送HTTP请求。HTTP请求的URL为:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET。
其中APPID为微信公众平台申请的开发者ID,APPSECRET为微信公众平台申请的开发者密码。具体实现代码如下:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class GetToken {
public static void main(String[] args) {
String appId = "yourAppId";
String appSecret = "yourAppSecret";
String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appId + "&secret=" + appSecret;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(tokenUrl);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
if (null != entity) {
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println(result);
}
} catch (ParseException | IOException e) {
e.printStackTrace();
}
}
}
3. 解析返回的JSON数据
获取到后台返回的JSON数据后,我们需要对JSON数据进行解析,提取出access_token值。这里我使用了json-lib这个第三方库。
具体实现代码如下:
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import net.sf.json.JSONObject;
import net.sf.json.JSONException;
import net.sf.json.util.JSONTokener;
public class JsonToken {
public static String parseJson(String json) {
String token = "";
try {
if (StringUtils.isNotEmpty(json)) {
Object obj = new JSONTokener(json).nextValue();
if (obj instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) obj;
if (jsonObject.containsKey("access_token")) {
token = jsonObject.getString("access_token");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return token;
}
}
4. 封装获取access_token的工具类
为了方便使用,我们可以封装一个获取微信公众平台access_token的工具类。
具体实现代码如下:
public class Access_token_task {
private static final String APP_ID = "yourAppId";
private static final String APP_SECRET = "yourAppSecret";
private static String access_token = "";
private static long refresh_token_time = 0;
/**
*
* @return 微信公众平台的access_token
*/
public static String getAccessToken() {
long now = System.currentTimeMillis();
if ((now - refresh_token_time) > 7200 * 1000) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ APP_ID + "&secret=" + APP_SECRET;
HttpClient httpclient = new HttpClient();
HttpMethod method = new GetMethod(url);
BufferedReader br = null;
try {
int statusCode = httpclient.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
String response = method.getResponseBodyAsString();
JSONObject jsonObject = JSONObject.fromObject(response);
if (jsonObject.containsKey("access_token")) {
access_token = jsonObject.getString("access_token");
// 记录更新access_token的时间
refresh_token_time = now;
} else {
access_token = "";
}
} else {
access_token = "";
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
method.releaseConnection();
}
}
return access_token;
}
}
至此,我们使用Java实现了获取微信公众平台access_token的过程。