【问题标题】:Request doesn't use saved cookies in PersistentCookieStore请求不使用 PersistentCookieStore 中保存的 cookie
【发布时间】:2016-08-10 20:02:23
【问题描述】:

我在声明 cookie 存储时修复了我的应用程序中的崩溃和错误,但它没有保存 cookie 或在其他位置出现问题。

一开始我把这两行叫做:

AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore;

然后我有一个 POST:

public void postRequestLogin(String url, RequestParams params) {
    myCookieStore = new PersistentCookieStore(this);
    client.post(url, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            client.setCookieStore(myCookieStore);
            System.out.println(response);

            if(response.contains("Login successful!")) {
                TextView lblStatus = (TextView)findViewById(R.id.lblStatus);
                lblStatus.setText("Login successful!");
                getRequest("url");
            } else {
                TextView lblStatus = (TextView)findViewById(R.id.lblStatus);
                lblStatus.setText("Login failed!");
                TextView source = (TextView)findViewById(R.id.response_request);
                source.setText(response);
            }
        }
    });

}

然后它应该保存 Logincookies 并将其用于 GET 请求:

public void getRequest(String url) {
    myCookieStore = new PersistentCookieStore(this);
    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            client.setCookieStore(myCookieStore);
            System.out.println(response);
            TextView responseview = (TextView) findViewById(R.id.response_request);
            responseview.setText(response);
        }
    });
}

但它不使用 cookie。当我执行 GET 请求时,我已经登出。

编辑:我忘了说我使用了本教程中的库:http://loopj.com/android-async-http/

【问题讨论】:

  • 明确你的标题很重要,因为它使知道如何提供帮助的人更有可能看到你的问题。您不需要使用“Android”或“Java”之类的词,因为问题已经有标签。

标签: java android http cookies


【解决方案1】:

我认为问题在于您在请求完成后设置了 cookie 存储(在 onSuccess 方法中)。在发出请求之前尝试设置它:

myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);
client.post(url, params, new AsyncHttpResponseHandler() {

您还在为每个请求创建一个新的 cookie 存储。如果您执行多个请求会发生什么?它将创建一个新的 cookie 存储并使用它(新的 cookie 存储不会有您的 cookie)。尝试将这部分代码移动到您的构造函数中:

myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);

然后将其从其他函数中删除。

【讨论】:

  • @Phil 另外,我只是再次查看您的代码,您正在为每个请求创建一个新的 cookie 存储。您应该只调用一次new PersistentCookieStore()setCookieStore(可能在构造函数中)。
  • 好的,我现在只是在构造函数中完成了,工作正常,再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多