Android使用token維持登陸狀態的方法

來源:互聯網
上載者:User

標籤:into   data   tor   對象   break   short   edm   error   over   

什麼是token

token(令牌)是一串唯一的字串,通常由服務端產生,在註冊完成時返回給用戶端,用來標識此使用者,用戶端將此字串儲存在本地。在以後的網路請求時,用戶端先查詢本地的token,如果有則直接使用此令牌進行網路請求,沒有則提示未登入,轉到登陸註冊介面。

此外,還可以在服務端或者用戶端添加到期判別機制。

token的作用

token可以顯著減少服務端對使用者表的查詢,同時使使用者不必每次都登陸,提高了系統的可用性與健壯性。

使用SharedPreferences儲存token

擷取token並儲存

NetWorks.regPost(user, password, email, tel, new Observer<User>() {   @Override   public void onCompleted() {   }   @Override   public void onError(Throwable e) {        Log.e("LoginActivity",e.getLocalizedMessage()+"--"+e.getMessage());   }   @Override   public void onNext(User user) {    if(user.getmMessage().equals("success")){     MainActivity.instance.finish();//結束原來的首頁面     Toast.makeText(getApplicationContext(),"註冊成功",Toast.LENGTH_SHORT).show();     //token儲存到本地     SharedPreferences sp = getSharedPreferences("loginToken", 0);     SharedPreferences.Editor editor = sp.edit();     editor.putString("userId",user.getmUserId());     editor.putString("userName",user.getmUserName());     editor.putString("phone",user.getmPhone());     editor.putString("email",user.getmEmail());     editor.putString("headImageUrl",user.getmHeadImageUrl());     editor.commit();     Intent i = new Intent(RegActivity.this,MainActivity.class);     startActivity(i);     finish();    }else{     Toast.makeText(getApplicationContext(),"註冊失敗"+user.getmMessage(),Toast.LENGTH_SHORT).show();    }   }  });

我使用的是retrofit架構進行網路請求,上文是實現註冊功能的函數,在onNext()函數中擷取服務端返回的結果,這個架構自動把返回的json資料解析為對應的類對象(即上文中的user對象)。因為token的本質是唯一的字串,userId滿足這個要求,因為userId是由服務端產生且唯一,故我將userId作為token使用。

進行網路請求前查詢本地token

比如點擊側邊欄的頭像,如果未登入則需要跳轉到登陸介面,已經登陸則進入個人資訊介面。這時候,就需要查詢本地token進行判別。

private void initData() {  sp = getSharedPreferences("loginToken", 0);  name = sp.getString("userId", null);  userName = sp.getString("userName", null);  email = sp.getString("email", null);   }@Override public void onClick(View view) {  switch (view.getId()) {      case R.id.imageView:    if (name == null) {     Intent i = new Intent(MainActivity.this, LoginActivity.class);     startActivity(i);    } else {     Log.d("使用者ID", name);     Intent i = new Intent(MainActivity.this, PersonInfoActivity.class);     startActivity(i);    }    break;  } }

備忘

在此例中,我使用userId作為token,但並不建議這麼做,雖然這樣很簡單。因為userId顯然無法判別是否到期,如果我們需要實現token到期的判別,則可以採用將userId與日期拼接的方式。

此外,為了安全起見,不要在用戶端產生token。

Android使用token維持登陸狀態的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.