我在启动期间在 cookie 管理器上添加 cookie 时遇到问题。
我要解决的问题是-在登录响应期间以及在应用程序被终止或退出时在 Sharedprefrence 中添加 cookie,检索该 cookie 并添加到我的 cookie 存储中,以便主要活动将读取命令发送到服务器,服务器将看到cookie 并知道用户已经登录。
我面临的当前问题是 - 在登录期间,我能够将 cookie 保存到共享偏好中。当应用程序被杀死并重新启动时,我从共享偏好中获取 cookie 字符串,但是当我将它添加到我的 cookiemanager 时 - 它仍然需要我进入登录屏幕。此外,当我在日志中打印 Sharedprefrence 之后,我看到 URI 为空,而在应用程序中 - 当我设置 cookie 时 - 我看到我的 URI 与 cookie 获取域值匹配(不确定它是否完全像这样或不是)
Flow 是 Mainactivity 向服务器发送读取命令,如果服务器发现没有 cookie 并且用户未登录,则发送状态 0;否则 1. 如果状态为 0,则我转到登录活动,否则转到主屏幕活动。这工作正常,但只有当应用程序被杀死时,因为 cookie 被删除,它需要我进入登录屏幕。
下面是代码:-
我的主要活动/登录活动和主屏幕活动 - 为 httpconnection 调用具有异步任务的类 - 它写入共享首选项。
在 doInbackground 内部:-
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
List<HttpCookie> cookies = ((CookieManager)CookieHandler.getDefault()).getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d("LOG_TAG","no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
Context context1 = application.getContext();
SharedPreferences sharedPreferences = context1.getSharedPreferences("Myprefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie",cookies.get(i).toString());
editor.putString("URI",cookiedomain);
editor.commit();
}
}
应用类 -
public class application extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
application.context = getApplicationContext();
SharedPreferences settings = getSharedPreferences("Myprefs", 0);
String silent = settings.getString("cookie", null);
String uri = settings.getString("URI",null);
if (silent != null) {
if (uri != null) {
HttpCookie httpcookie = new HttpCookie("user", silent);
URI myuri = URI.create(uri);
cookieManager.getCookieStore().add(myuri,httpcookie);
}
}
}
public static Context getContext() {
return application.context;
}
如果有人可以帮助我,将不胜感激。我真的在这里打破了我的头。