Using session cookies with android volley library by JsonObjectRequest
Asked Answered
F

3

6

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

Forage answered 26/6, 2013 at 15:51 Comment(0)
T
5

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;
    }
Tangerine answered 22/9, 2015 at 1:16 Comment(2)
You are my hero!!Inheritable
if (cookie.contains("expires")) { what are you doing?! you have to parse date to check if it expires and not if it contains this string because it always contains it and you just remove it all the timeSarsenet
C
1
    BasicHttpParams mHttpParams = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 15000;
    HttpConnectionParams.setConnectionTimeout(mHttpParams, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 20000;
    HttpConnectionParams.setSoTimeout(mHttpParams, timeoutSocket);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    registry.register(new Scheme("https", sslSocketFactory, 443));

    /*ClientConnectionManager cm = new ThreadSafeClientConnManager(mHttpParams, registry);*/
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(/*cm,*/ mHttpParams);

    RequestQueue requestQueue = Volley.newRequestQueue(mContext.getApplicationContext(),new HttpClientStack(defaultHttpClient));
Corium answered 30/7, 2013 at 12:53 Comment(0)
S
1

I use Volley Android Library because it like AFNetworking in iOS. Easier and Faster previous. About Cookies Session when login success. I configured:

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

And it ran success. But, CookieManage just execute in larger 8 versionSDK.

Like: in AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

Hope it can help you! Thanks.

Schizophrenia answered 6/11, 2013 at 2:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.