標籤: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維持登陸狀態的方法