问题描述
当我宣布一个cookie商店时,我修复了我的应用程序中的崩溃和错误,但它没有保存cookie或在其他位置出现问题。
I fixed the crash and error in my app when I declared a cookie store, but it doesn't save the cookies or something went wrong at an other position.
首先我称这两行:
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore;
然后我有一个POST:
And then I have a 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请求:
Then it should save the Logincookies and use it for the GET Request:
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);
}
});
}
但它不使用cookies。当我执行GET请求时,我已经注销了。
But it doesn't use the cookies. When I do the GET Request I'm already logged out.
编辑:我忘了说我使用了本教程中的lib:
I forgot to say that I use a lib from this tutorial: http://loopj.com/android-async-http/
推荐答案
我认为问题是你在请求完成后设置了cookie存储(在 onSuccess
方法中)。在提出请求之前尝试设置它:
I think the problem is that you set the cookie store after the request has already completed (in the onSuccess
method). Try setting it before you make that request:
myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);
client.post(url, params, new AsyncHttpResponseHandler() {
你也是在每个请求上创建一个新的cookie存储。如果你做多个请求会发生什么?它会创建一个新的cookie存储并使用它(而新的cookie存储将没有你的cookie)。尝试移动这部分代码到你的构造函数:
You're also creating a new cookie store on every request. What happens if you do more than one request? It will create a new cookie store and use it (and the new cookie store won't have your cookies). Try moving this part of the code to your constructor:
myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);
然后将其从其他函数中删除。
Then remove it from the other functions.
这篇关于请求不会在PersistentCookieStore中使用已保存的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!