玩玩Java版之三:access_token及存储
access_token
官⽅参考⽂档:
基本说明:
access_token是的全局唯⼀接⼝调⽤凭据,调⽤各接⼝时都需使⽤access_token。开发者需要进⾏妥善保存。access_token 的存储⾄少要保留512个字符空间。access_token的有效期⽬前为2个⼩时,需定时刷新,重复获取将导致上次获取的access_token失效。
调⽤⽅式:
可以使⽤AppID和AppSecret调⽤本接⼝来获取access_token。AppID和AppSecret可在“公众平台-开发-基本配置”页中获得(需要已经成为开发者,且帐号没有异常状态)。调⽤接⼝时,请登录“公众平台-开发-基本配置”提前将服务器IP地址添加到IP⽩名单中,点击查看设置⽅法,否则将⽆法调⽤成功。
特别说明:建议开发者使⽤中控服务器统⼀获取和刷新Access_token,其他业务逻辑服务器所使⽤
的access_token均来⾃于该中控服务器,不应该各⾃去刷新,否则容易造成冲突,导致access_token覆盖⽽影响业务;
了解这些信息后,我们需要理解确定如下⼏点:
1、统⼀token调⽤⽅法,其他地⽅需⽤到token均采⽤本⽅法获取;
2、请求获取token信息接⼝的实现;
3、token数据存储⾄本地数据库;
4、判断是否需要重新获取token还是直接从本地数据库中查询;
下⾯来进⾏具体的实现:
⾸先看⼀下整体的类图:
那么在获取token时,可以根据appid和appsecret来获取,其中判断是否需要更新的⽅法为:
能否获取到当前仍有效的token:查询SQL如下:
对应表结构参考如下:
对应的java代码如下:如果能获取到,那么直接返回:
1/**
2    * 通过参数获取Token信息
3    * @param appID
4    * @param appSceret
5    * @return
6*/
7public Token getToken(String appID, String appSceret)
8    {
9        mAppID = appID;
10        mAppSceret = appSceret;
11
12// 1.确定是否要更新token,⽆需更新则直接直接返回获取的token
13if (updateToken())
17
18// 2. 如需更新
19if (!getTokenbyhttps(mAppID, mAppSceret))
20        {
21            System.out.println("获取失败!");
22return null;
23        }
24
25return mToken;
26    }
View Code
其中明细⽅法实现为:
1/**
2    * 获取Token信息
3    * @return
4*/
5private boolean updateToken()
6    {
7// 查询数据库数据,如果有则不⽤更新,⽆则需要更新
8        Connection con = null;
9        PreparedStatement stmt = null;
10        ResultSet rs = null;
11// 判断当前token是否在有效时间内
12        String sql = " select * from token where appid ='" + mAppID + "' and appsecret ='" + mAppSceret
13                + "' and ( current_timestamp -createtime) <expires_in order by createTime desc limit 0,1"; 14try
15        {
16// 创建数据库链接
17            con = Connection();
18// 创建处理器
19            stmt = con.prepareStatement(sql);
20// 查询Token,读取1条记录
21            rs = uteQuery();
22if (rs.next())
23            {
24                mToken.String("tokenid"));
25                mToken.String("token"));
26                mToken.setExpires_Int("expires_in"));
27                mToken.String("appid"));
28                mToken.String("appsecret"));
29            }
30else
31            {
32                System.out.println("未查询到对应token");
33return false;
34            }
35        }
36catch (Exception e)
37        {
38// TODO: handle exception
39return false;
iapp免费源码分享网站40        }
41
42        System.out.Token());
43
44return true;
45    }
View Code
如果需要获取新的token,则:
1/**
2    * 通过https请求获取token
3    * @param appID
4    * @param appSceret
5    * @return
6*/
7private boolean getTokenbyhttps(String appID, String appSceret)
8    {
9        String current_time = new Date().getTime() + "";
10
11try
12        {
16
17            String strResp = WeChatUtil.doHttpsGet(path, "");
18            System.out.println(strResp);
19
20// 解析获取的token信息
21            Map<String, Object> tMap = WeChatUtil.jsonToMap(strResp);
22
23            System.out.String());
24
25            mToken.MaxTokenID());
26            mToken.setToken((String) ("access_token"));
27            mToken.setExpires_in(Integer.parseInt((String) ("expires_in")));
28            mToken.setAppid(appID);
29            mToken.setAppsecret(appSceret);
30            mToken.setCreatetime(current_time);
31
32            System.out.Token());
33
34        }
35catch (HttpException e)
36        {
37// TODO Auto-generated catch block
38            e.printStackTrace();
39        }
40catch (IOException e)
41        {
42// TODO Auto-generated catch block
43            e.printStackTrace();
44        }
45
46// 存储token⾄数据库
47        saveToken(mToken);
48
49return true;
50    }
51
52/**
53    * 保存Token信息
54    * @return
55*/
56private boolean saveToken(Token token)
57    {
58        PreparedStatement pst = null;
59        Connection conn = null;
60try
61        {
62            Token tToken = token.clone();
63
64            System.out.Tokenid() + Token());
65
66            conn = Connection();
67// 创建预处理器
68            pst = conn.prepareStatement("insert into token(tokenid, token, expires_in,appid, appsecret,createtime) values (?,?,?,?,?,?)"); 69
70            pst.setString(1, Tokenid());
71            pst.setString(2, Token());
72            pst.setInt(3, Expires_in());
73            pst.setString(4, Appid());
74            pst.setString(5, Appsecret());
75long now = new Date().getTime();
76            pst.setTimestamp(6, new java.sql.Timestamp(now));
77            ute();
78
79        }
80catch (CloneNotSupportedException e)
81        {
82// TODO Auto-generated catch block
83            e.printStackTrace();
84return false;
85        }
86catch (SQLException e)
87        {
88// TODO Auto-generated catch block
89            e.printStackTrace();
90return false;
91        }
92catch (Exception e)
93        {
94// TODO: handle exception
95            System.out.println("出现额外异常");
96        }
对于https的GET和POST调⽤,可以写2个公共⽅法,具体实现可参考:
1/**
2    * HTTPS请求Get⽅法调⽤
3    * @param path
4    * @param requestData
5    * @return
6    * @throws HttpException
7    * @throws IOException
8*/
9public static String doHttpsGet(String path, String requestData) throws HttpException, IOException 10    {
11// 创建https请求,未默认证书,可⾃⾏添加
12// 设置编码
13        HttpClient httpClient = new HttpClient();
14        GetMethod getMethod = new GetMethod(path);
15        Params().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); 16
17        uteMethod(getMethod);
18
19// 读取内容
20byte[] responseBody = ResponseBody();
21        String strResp = new String(responseBody, "UTF-8");
22
23        System.out.println(strResp);
24
25        leaseConnection();
26
27return strResp;
28    }
29
30/**
31    * HTTPS请求Post⽅法调⽤
32    * @param path
33    * @param requestData
34    * @return
35    * @throws HttpException
36    * @throws IOException
37*/
38public static String doHttpsPost(String path, String requestData) throws HttpException, IOException 39    {
40// 创建https请求,未默认证书,可⾃⾏添加
41        String strResp ="";
42        HttpClient httpClient = new HttpClient();
43        PostMethod postMethod = new PostMethod(path);
44// 设置编码
45        Params().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); 46
47        System.out.println("path:" + path);
48        System.out.println("requestData:" + requestData);
49
50        postMethod.setRequestBody(requestData);
51
52long start = System.currentTimeMillis();
53// 执⾏getMethod
54int statusCode = uteMethod(postMethod);
55        System.out.println("cost:" + (System.currentTimeMillis() - start));
56// 失败
57if (statusCode != HttpStatus.SC_OK)
58        {
59            System.out.println("Method failed: " + StatusLine());
60// 读取内容
61byte[] responseBody = ResponseBody();
62// 处理内容
63            strResp = new String(responseBody, "UTF-8");
64            System.out.println(strResp);
65        }
66else
67        {
68// 读取内容
69byte[] responseBody = ResponseBody();
70            strResp = new String(responseBody, "UTF-8");
71            System.out.println("服务器返回:" + strResp);
72        }
73
74        leaseConnection();
75
需要加⼊返回是json,处理json 需要json对应的jar,另外需要⽤到httpclient 的jar包。
获取token后,要进⾏数据存储,再返回即可。
获取access_token 这⾥就结束了,后⾯的功能接⼝均需要⽤到 access_token,这⾥写的获取⽅法后⾯可以直接调⽤,很⽅便了哟~

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。