Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> 實戰Android仿人人客戶端之授權認證(用accessToken換取session

實戰Android仿人人客戶端之授權認證(用accessToken換取session

編輯:Android開發實例

        網絡模塊的處理,基本上已講解完,後面若遇到其他的網絡處理需求再調整。這篇接著 實戰Android仿人人客戶端之人人授權訪問界面  繼續,前面聊到打開人人授權界面,當用戶輸入訪問人人的賬號和密碼,點擊“登錄”按鈕後,若成功服務器端會返回accessToken。之後怎麼處理,下面開始這篇的講述:

一、對服務器端返回的accessToken進行處理

       服務器端會返回accessToken

  1. 195789%7C6.7faefec2274182195287028d00323781.2592000.1367118000-461345584 

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

  1. 195789|6.7faefec2274182195287028d00323781.2592000.1367118000-461345584 

        需要做的處理:

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

二、用accessToken通過HTTP協議POST方式交換session_key、session_secret和userId。

       1、發起網絡請求

  1. Map<String, String> parameter = new HashMap<String, String>();  
  2.       parameter.put("oauth_token", accessToken);  
  3.       AsyncBaseRequest asyncRequest = new AsyncHttpPost(Constant.SESSION_KEY_URL, parameter,  
  4.               new ParseCallback (){  
  5.  
  6.                   @Override 
  7.                   public Boolean parse(String json) throws JSONException {  
  8.                       Log.e(TAG, "result = " + json);  
  9.                         
  10.                       return false;  
  11.                   }  
  12.             
  13.       },   
  14.       new  ResultCallback(){  
  15.  
  16.           @Override 
  17.           public void onSuccess(final Object result) {  
  18.               mHandler.post(new Runnable() {  
  19.                     
  20.                   @Override 
  21.                   public void run() {  
  22.                      
  23.                   }  
  24.               });  
  25.           }  
  26.  
  27.           @Override 
  28.           public void onFail(int errorCode) {  
  29.               Log.e(TAG, "網絡請求返回的errorCode = " + errorCode);                  
  30.           }  
  31.             
  32.       });  
  33.         
  34.       mDefaultThreadPool.execute(asyncRequest);  
  35.       mAsyncRequests.add(asyncRequest);  

p#副標題#e#

        2、解析網絡返回的JSON字符串:

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

  1. {  
  2.    "renren_token":  
  3.    {  
  4.        "session_secret":"52e95c7b02abb0a80a4a80116438063a",  
  5.        "expires_in":2595334,  
  6.        "session_key":"6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584" 
  7.    },  
  8.    "oauth_token":"195789|6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584",  
  9.    "user":  
  10.    {  
  11.        "id":461345584  
  12.    }  
  13. }  

                對JSON字符串進行解析:

  1. JSONObject jsonObject = new JSONObject(json);  
  2.  
  3. JSONObject jsonRenrenToken = jsonObject.getJSONObject("renren_token");  
  4. String session_key = jsonRenrenToken.getString("session_key");  
  5. String session_secret = jsonRenrenToken.getString("session_secret");  
  6. long expires_in = jsonRenrenToken.getLong("expires_in");  
  7.  
  8. String oauth_token = jsonObject.getString("oauth_token");  
  9. long userId = jsonObject.getJSONObject("user").getLong("id");  
  10.  
  11. // 對Session過期時間進行處理,  Session過期時間 = 系統當前的時間 + 服務器端返回的Session過期時間。  
  12. long create_session_time = System.currentTimeMillis();  
  13. expires_in = create_session_time + expires_in*1000; // 服務器端返回的Session過期時間單位為秒,因此需要乘以1000  
  14.  
  15. StringBuilder authResult = new StringBuilder();  
  16. authResult.append(" oauth_token = ").append(oauth_token);  
  17. authResult.append("\n session_key = ").append(session_key);  
  18. authResult.append("\n session_secret = ").append(session_secret);  
  19. authResult.append("\n expires_in = ").append(expires_in);  
  20. authResult.append("\n userId = ").append(userId);  
  21.  
  22. Log.i(TAG, "解析後的值:\n" + authResult.toString());  

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

  1. // 本地存儲Authorization授權認證數據  
  2. Editor editor = mContext.getSharedPreferences("auth_config", Context.MODE_PRIVATE).edit();  
  3. editor.putString("session_key", session_key);  
  4. editor.putString("session_secret", session_secret);  
  5. editor.putLong("expires_in", expires_in);  
  6. editor.putLong("create_session_time", create_session_time);  
  7. editor.putString("oauth_token", oauth_token);  
  8. editor.putLong("userId", userId);  
  9. editor.commit();  

四、切換界面到應用主界面

  1. new  ResultCallback(){  
  2.  
  3.          @Override 
  4.          public void onSuccess(final Object result) {  
  5.              mHandler.post(new Runnable() {  
  6.                    
  7.                  @Override 
  8.                  public void run() {  
  9.                      if((Boolean)result)  
  10.                      {  
  11.                          Intent intent = new Intent(AuthActivity.this, EveryoneActivity.class);  
  12.                          AuthActivity.this.startActivity(intent);  
  13.                      } else {  
  14.                          Log.e(TAG, "網絡請求返回的JSON值為NULL");  
  15.                      }  
  16.                  }  
  17.              });  
  18.          }  
  19.  
  20.          @Override 
  21.          public void onFail(int errorCode) {  
  22.              Log.e(TAG, "網絡請求返回的errorCode = " + errorCode);                  
  23.          }  
  24.            
  25.      }  

使用accessToken交換session等完整的代碼如下:

  1. /**  
  2.    * 通過accessToken換取session_key、session_secret和userId  
  3.    * @param accessToken  
  4.    */ 
  5.   private void exchangeSessionKey(String accessToken) {  
  6.       if (accessToken == null || accessToken.length() < 1) {  
  7.           return;  
  8.       }  
  9.         
  10.       Map<String, String> parameter = new HashMap<String, String>();  
  11.       parameter.put("oauth_token", accessToken);  
  12.       AsyncBaseRequest asyncRequest = new AsyncHttpPost(Constant.SESSION_KEY_URL, parameter,  
  13.               new ParseCallback (){  
  14.  
  15.                   @Override 
  16.                   public Boolean parse(String json) throws JSONException {  
  17.                       Log.e(TAG, "result = " + json);  
  18.                       if(!TextUtils.isEmpty(json)){  
  19.                             
  20.                           // 服務器端返回的JSON字符串:  
  21.                          /*{  
  22.                              "renren_token":  
  23.                              {  
  24.                                  "session_secret":"52e95c7b02abb0a80a4a80116438063a",  
  25.                                  "expires_in":2595334,  
  26.                                  "session_key":"6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584"  
  27.                              },  
  28.                              "oauth_token":"195789|6.8fed55fdfd5c027c2ecb0ac50859f97c.2592000.1367121600-461345584",  
  29.                              "user":  
  30.                              {  
  31.                                  "id":461345584  
  32.                              }  
  33.                           }*/ 
  34.  
  35.                           // 解析JSON  
  36.                           JSONObject jsonObject = new JSONObject(json);  
  37.                             
  38.                           JSONObject jsonRenrenToken = jsonObject.getJSONObject("renren_token");  
  39.                           String session_key = jsonRenrenToken.getString("session_key");  
  40.                           String session_secret = jsonRenrenToken.getString("session_secret");  
  41.                           long expires_in = jsonRenrenToken.getLong("expires_in");  
  42.                             
  43.                           String oauth_token = jsonObject.getString("oauth_token");  
  44.                           long userId = jsonObject.getJSONObject("user").getLong("id");  
  45.                             
  46.                           // 對Session過期時間進行處理,  Session過期時間 = 系統當前的時間 + 服務器端返回的Session過期時間。  
  47.                           long create_session_time = System.currentTimeMillis();  
  48.                           expires_in = create_session_time + expires_in*1000; // 服務器端返回的Session過期時間單位為秒,因此需要乘以1000  
  49.                             
  50.                           StringBuilder authResult = new StringBuilder();  
  51.                           authResult.append(" oauth_token = ").append(oauth_token);  
  52.                           authResult.append("\n session_key = ").append(session_key);  
  53.                           authResult.append("\n session_secret = ").append(session_secret);  
  54.                           authResult.append("\n expires_in = ").append(expires_in);  
  55.                           authResult.append("\n userId = ").append(userId);  
  56.                             
  57.                           Log.i(TAG, "解析後的值:\n" + authResult.toString());  
  58.                             
  59.                           // 本地存儲Authorization授權認證數據  
  60.                           Editor editor = mContext.getSharedPreferences("auth_config", Context.MODE_PRIVATE).edit();  
  61.                           editor.putString("session_key", session_key);  
  62.                           editor.putString("session_secret", session_secret);  
  63.                           editor.putLong("expires_in", expires_in);  
  64.                           editor.putLong("create_session_time", create_session_time);  
  65.                           editor.putString("oauth_token", oauth_token);  
  66.                           editor.putLong("userId", userId);  
  67.                           editor.commit();  
  68.  
  69.                           return true;  
  70.                             
  71.                       }  
  72.                       return false;  
  73.                   }  
  74.             
  75.       },   
  76.       new  ResultCallback(){  
  77.  
  78.           @Override 
  79.           public void onSuccess(final Object result) {  
  80.               mHandler.post(new Runnable() {  
  81.                     
  82.                   @Override 
  83.                   public void run() {  
  84.                       if((Boolean)result)  
  85.                       {  
  86.                           Intent intent = new Intent(AuthActivity.this, EveryoneActivity.class);  
  87.                           AuthActivity.this.startActivity(intent);  
  88.                       } else {  
  89.                           Log.e(TAG, "網絡請求返回的JSON值為NULL");  
  90.                       }  
  91.                   }  
  92.               });  
  93.           }  
  94.  
  95.           @Override 
  96.           public void onFail(int errorCode) {  
  97.               Log.e(TAG, "網絡請求返回的errorCode = " + errorCode);                  
  98.           }  
  99.             
  100.       });  
  101.         
  102.       mDefaultThreadPool.execute(asyncRequest);  
  103.       mAsyncRequests.add(asyncRequest);  
  104.   }  

轉自:http://blog.csdn.net/android_ls/article/details/8741383

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved