AccessToken的定时获取

https://blog.csdn.net/ly20116/article/details/51086662

原文链接

当需要运行线程获取值时

public class weixin {
    public static void main(String[] args) throws Exception {
        new TokenThread().run();
        Thread.sleep(1000*10); 
        try {
            String access_token= TokenThread.accessToken.getAccessToken();
            if (access_token==null){
                System.out.println("票据没有")  ;
            }else {
                System.out.println("票据" + access_token);
                String path = "D:/Taa/tf1.mp4";
                String mediaID = WeixinUtil.upload(path, access_token, "video");
                System.out.println("mediaID是:" + mediaID);
            } } catch (Exception e) {
            e.printStackTrace(); } }}

2.另一个

http://www.cnblogs.com/fengzheng/p/5027630.html

但是都是用一个线程,sleep方法,太吃内存了

3.Java自带的定时器TimerTask

public class TokenTimer extends TimerTask {
public static String APPID =“”;
public static String APPSECRET= “”;
public static AccessToken accessToken=null;
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
@Override
public void run() {
    accessToken=this.getAccessToken();

    if (accessToken!=null){
        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Calendar"+sf.format(calendar.getTime()));//打印当前的执行时间
        System.out.println("票据"+accessToken.getAccessToken());
    }
    return;
    
}
//获取AccessToken
    public  AccessToken getAccessToken() {
    String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
    JSONObject jsonObject = WeixinUtil.httpsRequest(url,"GET",null);
    AccessToken accessToken = new AccessToken();
    System.out.println(url);
    if (jsonObject != null) {
        accessToken.setAccessToken(jsonObject.getString("access_token"));
        accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
    }
    return accessToken;
}}

 

 

public class MyTimerText {
    public static void main(String[] args) {
        Timer timer=new Timer();
        TokenTimer tokenTimer=new TokenTimer();
        timer.schedule(tokenTimer,1000);
    }
}

这个也一般,而且容易崩溃。

如果小伙伴有更好的方法,欢迎一起交流哦。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值