CookieManager not sending cookie after first and second request

486 views Asked by At

Currently working on an Android app with CookieManager..

I am trying to do PUT requests using a for loop but for some odd reason, only the first two requests succeed. I asked the server guy for help and he indicated that the other PUT requests fail because they do not have a cookie attached.

This is the for loop that I'm using.

for(int i = 0; i < userList.size(); i++) {

        User user = userList.get(i);

        String url = apiURL;
        String address = user.getEmail() == null ? "nil":user.getEmail();

        String jsonString = "{build:\"" + String.valueOf(BuildConfig.VERSION_CODE) + "\",device_id:\"" + ((MainActivity)activity).tmDevice + "\",platform:\"android\",\n" +
                "                     type:\"User\",\n" +
                "                       id:\"" + String.valueOf(user.getId()) + "\",\n" +
                "               first_name:\"" + user.getFirstName() + "\",\n" +
                "                last_name:\"" + user.getLastName() + "\",\n" +
                "                     name:\"" + user.getName() + "\",\n" +
                "                    image:{\n" +
                "                type:\"UserPhoto\",\n" +
                "                  id:\"1a035500-012f-1cc2-9d22-96a73beda35e\"\n" +
                "            },\n" +
                "                   emails:[\n" +
                "                 {\n" +
                "                       type:\"Email\",\n" +
                "                    address:" + address + "\n" +
                "                }\n" +
                "            ],\n" +
                "            phone_numbers:[]\n" +
                "        }";

        JSONObject js = null;
        try {
            js = new JSONObject(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final JSONObject finalJs = js;
        JsonObjectRequest jsObjRequest = new JsonObjectRequest(
                Request.Method.PUT,url, finalJs,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("putresponse", String.valueOf(response));
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("puterror", String.valueOf(error));
            }

        });
        VolleySingleton.getInstance((MainActivity) activity).addToRequestQueue(jsObjRequest);

 }

This is the code for setting CookieManager.

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

Even the GET requests right before the PUT requests work fine.. Any help?

1

There are 1 answers

0
Maher Ismaail On

After 3 days of seaching and reading about CookieManager

I finally find and make a perfect solution :

static CookieManager myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);;

final public static void saveCookies(HttpURLConnection connection , Context context) {
    Map<String, List<String>> headerFields = connection.getHeaderFields();

    List<String> cookiesHeader = null;
    try {
        cookiesHeader = headerFields.get("Set-Cookie");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (cookiesHeader != null && myCookies != null) {
        for (String cookie : cookiesHeader) {
            try {
                cookie = cookie.replace("\"", "");
                myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
                String new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());

                PreferenceManager.getDefaultSharedPreferences(context).edit().putString("cookie", new_cookie).commit();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

final public static void loadCookies(HttpURLConnection connection , Context context) {
    if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
        connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
    }
    else {
        String new_cookie = PreferenceManager.getDefaultSharedPreferences(context).getString("cookie" , "");
        connection.setRequestProperty("Cookie", new_cookie );
    }
}