版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27612843/article/details/78110064
通过阅读微信开发者文档会发现——>access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
在获取access_token时使用的是get请求,那么也就是说我们需要在通过httpclient发送以个get请求
最后返回的是一个json格式
下面直接贴入代码
此时已经可以获取到access_token了,但是还不满足我们的开发使用,因为在微信对于access_token有时间要求,access_token会在两个小时后失效,并且一天只能调用2000次,所以我们需要对代码进行一个封装,下面是真正使用的
-
package com.website.commons.web.utils;
-
-
import java.io.IOException;
-
-
import org.apache.http.HttpResponse;
-
import org.apache.http.HttpStatus;
-
import org.apache.http.client.ClientProtocolException;
-
import org.apache.http.client.HttpClient;
-
import org.apache.http.client.methods.HttpGet;
-
import org.apache.http.impl.client.DefaultHttpClient;
-
import org.apache.http.util.EntityUtils;
-
import org.json.JSONObject;
-
-
public
class Constant {
-
-
public
static
final String APPID =
"你的APPID";
-
-
public
static
final String APPSECRET =
"你的APPSECRET";
-
-
/**全局token 所有与微信有交互的前提 */
-
public
static String ACCESS_TOKEN;
-
-
/**全局token上次获取事件 */
-
public
static
long LASTTOKENTIME;
-
-
/**
-
* 获取全局token方法
-
* 该方法通过使用HttpClient发送http请求,HttpGet()发送请求
-
* 微信返回的json中access_token是我们的全局token
-
*/
-
public static synchronized void getAccess_token(){
-
if(ACCESS_TOKEN ==
null || System.currentTimeMillis() - LASTTOKENTIME >
7000*
1000){
-
try {
-
//请求access_token地址
-
String url =
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9c3336b0bdb29172&secret=e22ea5453c6c10326045a00112c873f4";
-
//创建提交方式
-
HttpGet httpGet =
new HttpGet(url);
-
//获取到httpclien
-
HttpClient httpClient =
new DefaultHttpClient();
-
//发送请求并得到响应
-
HttpResponse response = httpClient.execute(httpGet);
-
//判断请求是否成功
-
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
-
//将得到的响应转为String类型
-
String str = EntityUtils.toString(response.getEntity(),
"utf-8");
-
//字符串转json
-
JSONObject jsonObject =
new JSONObject(str);
-
//输出access_token
-
System.out.println((String) jsonObject.get(
"access_token"));
-
//给静态变量赋值,获取到access_token
-
ACCESS_TOKEN = (String) jsonObject.get(
"access_token");
-
//给获取access_token时间赋值,方便下此次获取时进行判断
-
LASTTOKENTIME = System.currentTimeMillis();
-
}
-
}
catch (ClientProtocolException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
}
-
}
-
public static void main(String[] args) {
-
getAccess_token();
-
}
-
}
ok!代码完工,根据大家的编码风格可以做改动