Using session cookies with android volley library by JsonObjectRequest

人走茶凉 提交于 2020-01-12 03:54:49

问题


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


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/17324804/using-session-cookies-with-android-volley-library-by-jsonobjectrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!