Android仿人人客户端(v5.7.1)——授权认证(用accessToken换取session_key、session_secret和userId)

转载请标明出处:http://blog.csdn.net/android_ls/article/details/8741383

        网络模块的处理,基本上已讲解完,后面若遇到其他的网络处理需求再调整。这篇接着仿人人客户端(v5.7.1)——人人授权访问界面  继续,前面聊到打开人人授权界面,当用户输入访问人人的账号和密码,点击“登录”按钮后,若成功服务器端会返回accessToken。之后怎么处理,下面开始这篇的讲述:

一、对服务器端返回的accessToken进行处理

       服务器端会返回accessToken

195789%7C6.7faefec2274182195287028d00323781.2592000.1367118000-461345584

       通过运行人人官方提供的Demo,打印LOG如下:

195789|6.7faefec2274182195287028d00323781.2592000.1367118000-461345584

        需要做的处理:

 accessToken = accessToken.replace("%7C", "|");

                   

二、用accessToken通过HTTP协议POST方式交换session_key、session_secret和userId。

       1、发起网络请求

  Map<String, String> parameter = new HashMap<String, String>();

        parameter.put("oauth_token", accessToken);

        AsyncBaseRequest asyncRequest = new AsyncHttpPost(Constant.SESSION_KEY_URL, parameter,

                new ParseCallback (){



                    @Override

                    public Boolean parse(String json) throws JSONException {

                        Log.e(TAG, "result = " + json);

                        

                        return false;

                    }

            

        }, 

        new  ResultCallback(){



            @Override

            public void onSuccess(final Object result) {

                mHandler.post(new Runnable() {

                    

                    @Override

                    public void run() {

                     

                    }

                });

            }



            @Override

            public void onFail(int errorCode) {

                Log.e(TAG, "网络请求返回的errorCode = " + errorCode);                

            }

            

        });

        

        mDefaultThreadPool.execute(asyncRequest);

        mAsyncRequests.add(asyncRequest);

        2、解析网络返回的JSON字符串:

              服务器端返回的JSON字符串:

                            {

                               "renren_token":

                               {

                                   "session_secret":"52e95c7b02abb0a80a4a80116438063a",

                                   "expires_in":2595334,

                                   "session_key":"6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584"

                               },

                               "oauth_token":"195789|6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584",

                               "user":

                               {

                                   "id":461345584

                               }

                            }

                对JSON字符串进行解析:

                            JSONObject jsonObject = new JSONObject(json);

                            

                            JSONObject jsonRenrenToken = jsonObject.getJSONObject("renren_token");

                            String session_key = jsonRenrenToken.getString("session_key");

                            String session_secret = jsonRenrenToken.getString("session_secret");

                            long expires_in = jsonRenrenToken.getLong("expires_in");

                            

                            String oauth_token = jsonObject.getString("oauth_token");

                            long userId = jsonObject.getJSONObject("user").getLong("id");

                            

                            // 对Session过期时间进行处理,  Session过期时间 = 系统当前的时间 + 服务器端返回的Session过期时间。

                            long create_session_time = System.currentTimeMillis();

                            expires_in = create_session_time + expires_in*1000; // 服务器端返回的Session过期时间单位为秒,因此需要乘以1000

                            

                            StringBuilder authResult = new StringBuilder();

                            authResult.append(" oauth_token = ").append(oauth_token);

                            authResult.append("\n session_key = ").append(session_key);

                            authResult.append("\n session_secret = ").append(session_secret);

                            authResult.append("\n expires_in = ").append(expires_in);

                            authResult.append("\n userId = ").append(userId);

                            

                            Log.i(TAG, "解析后的值:\n" + authResult.toString());

三、采用SharedPreferences在本地保存Auth授权的信息,以便以后使用。

                            // 本地存储Authorization授权认证数据

                            Editor editor = mContext.getSharedPreferences("auth_config", Context.MODE_PRIVATE).edit();

                            editor.putString("session_key", session_key);

                            editor.putString("session_secret", session_secret);

                            editor.putLong("expires_in", expires_in);

                            editor.putLong("create_session_time", create_session_time);

                            editor.putString("oauth_token", oauth_token);

                            editor.putLong("userId", userId);

                            editor.commit();

四、切换界面到应用主界面

   new  ResultCallback(){



            @Override

            public void onSuccess(final Object result) {

                mHandler.post(new Runnable() {

                    

                    @Override

                    public void run() {

                        if((Boolean)result)

                        {

                            Intent intent = new Intent(AuthActivity.this, EveryoneActivity.class);

                            AuthActivity.this.startActivity(intent);

                        } else {

                            Log.e(TAG, "网络请求返回的JSON值为NULL");

                        }

                    }

                });

            }



            @Override

            public void onFail(int errorCode) {

                Log.e(TAG, "网络请求返回的errorCode = " + errorCode);                

            }

            

        }

使用accessToken交换session等完整的代码如下:

  /**

     * 通过accessToken换取session_key、session_secret和userId

     * @param accessToken

     */

    private void exchangeSessionKey(String accessToken) {

        if (accessToken == null || accessToken.length() < 1) {

            return;

        }

        

        Map<String, String> parameter = new HashMap<String, String>();

        parameter.put("oauth_token", accessToken);

        AsyncBaseRequest asyncRequest = new AsyncHttpPost(Constant.SESSION_KEY_URL, parameter,

                new ParseCallback (){



                    @Override

                    public Boolean parse(String json) throws JSONException {

                        Log.e(TAG, "result = " + json);

                        if(!TextUtils.isEmpty(json)){

                            

                            // 服务器端返回的JSON字符串:

                           /*{

                               "renren_token":

                               {

                                   "session_secret":"52e95c7b02abb0a80a4a80116438063a",

                                   "expires_in":2595334,

                                   "session_key":"6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584"

                               },

                               "oauth_token":"195789|6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584",

                               "user":

                               {

                                   "id":461345584

                               }

                            }*/



                            // 解析JSON

                            JSONObject jsonObject = new JSONObject(json);

                            

                            JSONObject jsonRenrenToken = jsonObject.getJSONObject("renren_token");

                            String session_key = jsonRenrenToken.getString("session_key");

                            String session_secret = jsonRenrenToken.getString("session_secret");

                            long expires_in = jsonRenrenToken.getLong("expires_in");

                            

                            String oauth_token = jsonObject.getString("oauth_token");

                            long userId = jsonObject.getJSONObject("user").getLong("id");

                            

                            // 对Session过期时间进行处理,  Session过期时间 = 系统当前的时间 + 服务器端返回的Session过期时间。

                            long create_session_time = System.currentTimeMillis();

                            expires_in = create_session_time + expires_in*1000; // 服务器端返回的Session过期时间单位为秒,因此需要乘以1000

                            

                            StringBuilder authResult = new StringBuilder();

                            authResult.append(" oauth_token = ").append(oauth_token);

                            authResult.append("\n session_key = ").append(session_key);

                            authResult.append("\n session_secret = ").append(session_secret);

                            authResult.append("\n expires_in = ").append(expires_in);

                            authResult.append("\n userId = ").append(userId);

                            

                            Log.i(TAG, "解析后的值:\n" + authResult.toString());

                            

                            // 本地存储Authorization授权认证数据

                            Editor editor = mContext.getSharedPreferences("auth_config", Context.MODE_PRIVATE).edit();

                            editor.putString("session_key", session_key);

                            editor.putString("session_secret", session_secret);

                            editor.putLong("expires_in", expires_in);

                            editor.putLong("create_session_time", create_session_time);

                            editor.putString("oauth_token", oauth_token);

                            editor.putLong("userId", userId);

                            editor.commit();



                            return true;

                            

                        }

                        return false;

                    }

            

        }, 

        new  ResultCallback(){



            @Override

            public void onSuccess(final Object result) {

                mHandler.post(new Runnable() {

                    

                    @Override

                    public void run() {

                        if((Boolean)result)

                        {

                            Intent intent = new Intent(AuthActivity.this, EveryoneActivity.class);

                            AuthActivity.this.startActivity(intent);

                        } else {

                            Log.e(TAG, "网络请求返回的JSON值为NULL");

                        }

                    }

                });

            }



            @Override

            public void onFail(int errorCode) {

                Log.e(TAG, "网络请求返回的errorCode = " + errorCode);                

            }

            

        });

        

        mDefaultThreadPool.execute(asyncRequest);

        mAsyncRequests.add(asyncRequest);

    }

好了就先到这里吧,不早了,晚安!

 

你可能感兴趣的:(android)