什么是token

token(令牌)是一串唯一的字符串,通常由服务端生成,在注册完成时返回给客户端,用来标识此用户,客户端将此字符串存储在本地。在以后的网络请求时,客户端先查询本地的token,如果有则直接使用此令牌进行网络请求,没有则提示未登录,转到登陆注册界面。

此外,还可以在服务端或者客户端添加过期判别机制。

token的作用
token可以显著减少服务端对用户表的查询,同时使用户不必每次都登陆,提高了系统的可用性与健壮性。
使用SharedPreferences保存token
获取token并保存
NetWorks.regPost(user, password, email, tel, new Observer() {
@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与日期拼接的方式。