How can I use session cookies using the volley library with a request like this?
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//Response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Error
}
});
queue.add(jsObjRequest);
thanks
This is the way I did to save cookies using Volley with JsonObjectRequest
The idea is to capture the Set-Cookie header that comes back with my Json request and then save it in preferences
Request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
url,
(String)param,
requestFuture, requestFuture){
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Show.m("getHeaders");
Map<String,String> headers = new HashMap<String, String>();
headers.put("Accept","application/json");
if(!MyApplication.getCookie(context).equals("")){
String cookie = MyApplication.getCookie(context);
Show.m("Cookie to load from preferences: " + cookie);
headers.put("Cookie", cookie);
}
return headers;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
Map headers = response.headers;
String cookie = (String)headers.get("Set-Cookie");
MyApplication.saveCookie(context, cookie);
Show.m("Cookie to save to preferences: " + cookie);
return super.parseNetworkResponse(response);
}
};
Preferences
public static void saveCookie(Context context, String cookie) {
if (cookie == null) {
return;
}
// Save in the preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
if (null == sharedPreferences) {
return;
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", cookie);
editor.commit();
}
public static String getCookie(Context context)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String cookie = sharedPreferences.getString("cookie", "");
if (cookie.contains("expires")) {
removeCookie(context);
return "";
}
return cookie;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With