Ilias Ilias - 6 months ago 191
Android Question

Get cookie from website using volley

I'm trying to get an identification cookie sent from a website, and for this i'm using Volley library.

First of all, yes i have searched this subject extensively for the past couple of days and using all the answers i managed to rack up this code:

public class Login extends AppCompatActivity {
StringRequest stringRequest = null;
RequestQueue queue;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
queue = Volley.newRequestQueue(this);
Button b = (Button) findViewById(R.id.bauth);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String url = "http://daviddurand.info/D228/pizza/?action=login&user=david";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
try {
Log.d("URI 1", manager.getCookieStore().get(new URI("http://daviddurand.info/D228/pizza/?action=login&user=david")).toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("URIS", manager.getCookieStore().getURIs().toString());
Log.d("COOKIE", manager.getCookieStore().getCookies().toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
});

}


}

Which does not return anything more than empty brackets, so i'm guessing something(s) wrong..
For starters am i heading the right way here? and what exactly do i need to add to make this work?

Answer

you dont need to put this:

CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);

in your response. but only once before you start making calls.

Using CookieHandler HttpURLConnection, which apparently is the http stack you use :), takes care of the cookies so you need to take care of that in Volley itself.

so you can do

CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

just before queue = Volley.newRequestQueue(this);

Comments