Phil Phil - 4 months ago 19
HTTP Question

Request doesn't use saved cookies in PersistentCookieStore

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.

At first I call these 2 lines:

AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore;


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);
}
}
});

}


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);
}
});
}


But it doesn't use the cookies. When I do the GET Request I'm already logged out.

Edit: I forgot to say that I use a lib from this tutorial: http://loopj.com/android-async-http/

Answer

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() {

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.