android - 使用改造和共享偏好注销
问题描述
我想在我的 android 应用程序中执行 Signout 功能。首先,我使用改造进行登录,现在,我想使用改造注销。我正在传递 Authrazation 令牌,如果我不使用令牌,则在标题中我将收到此错误“获取响应 http/1.1,代码 = 403 , message=Forbidden,url=https:/auth/user/logout "。如何使用 Retrofit 进行注销,并且我得到响应http/1.1,code=403,message=Forbidden,url=https://auth/user/logout,即使在传递令牌后,响应正文为空,它显示。该怎么办?
轮廓片段
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SessionMaintain.init(getActivity());
//read string in shared preference.
String token = SessionMaintain.read(SessionMaintain.TOKEN_USER, null);
Integer userId = SessionMaintain.read(SessionMaintain.USER_ID, 0);
logout(userId,token);
}
});
}
private void logout(Integer userId,String authorization) {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<LogResponse> logoutCall = apiInterface.signOut(userId,authorization);
logoutCall.enqueue(new Callback<LogResponse>() {
@Override
public void onResponse(Call<LogResponse> call, Response<LogResponse> response) {
Log.d("LogResponse",response.toString());
if(response.isSuccessful()){
LogResponse lresponse = response.body();
lresponse.getMessage();
Log.d("Token","Response"+response.body().getMessage());
Intent i = new Intent(getActivity(), LoginActivity.class);
startActivity(i);
SessionMaintain.clear();
}
}
共享偏好
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
模型
@SerializedName("message")
public String message;
接口交互
@FormUrlEncoded
@POST("auth/user/logout")
Call<LogResponse> signOut(@Field("user_Id") Integer user_id,
@Header("Authorization") String authorization);
解决方案
假设当您从注销 http 调用中获得成功响应时,您需要清除用户会话数据。
将以下函数添加到您的SessionMaintain
类中:
public static void clear() {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.clear();
prefsEditor.commit();
}
并在您从注销服务获得成功响应时使用它,如下所示:
@Override
public void onResponse(Call<LogResponse> call, Response<LogResponse> response)
{
Log.d("LogResponse", response.toString());
if (response.isSuccessful()) {
// here
SessionMaintain.clear()
}
}
推荐阅读
- php - PHP 卷码 400 [API]
- java - 在特定时间停止警报管理器
- c - 使用辅助指针操作 c 字符串后出现分段错误
- java - 将字符串转换为自定义标准格式
- python - openpyxl - 在现有合并单元格的 excel 文件中添加新行
- java - JavaFX(部分)隐藏网格窗格外的图像
- r - 在R中的data.frame中插入一行
- angular - 角度 4 FileReader onloadend 没有在 IE11 上被调用
- javascript - 为什么我不能在 Chrome 中声明一个与函数体同名的 let 变量
- angular - Angular 5 ngsubmit 在添加删除的模式弹出窗口中不起作用