1


I am working on Android with Volley, I need to do an HTTP request to get some cookies, the issue that the cookie I want to retrieve isn't in the header Set-Cookie but in the cookies section. enter image description here

I tried everything with Volley, but couldn't access to that part.
Is there any way to get these cookies?
thank you very much

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 2
    Possible duplicate of [Using cookies with Android volley library](https://stackoverflow.com/questions/16680701/using-cookies-with-android-volley-library) – Soham Apr 09 '19 at 09:01
  • this post talks about how to set a cookie in a request, my question is the opposite, how to retrieve a cookie :) – Abderrahmane Kaci Aissa Apr 09 '19 at 09:09

4 Answers4

1

Finally found the answer, here is the answer :

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

           OkHttpClient.Builder client = new OkHttpClient().newBuilder().cookieJar(new JavaNetCookieJar(manager));

            RequestBody reqbody = RequestBody.create(null, new byte[0]);
            Request request = new Request
                   .Builder()
                   .url(Utility.getRestaurationUrl(context).concat("/login/jwt/"))
                    .method("POST",reqbody)
                   .addHeader("Authorization",token)
                   .build();
            try {
                Response response = client.build().newCall(request).execute();
                List<HttpCookie> cook = manager.getCookieStore().getCookies();
            } catch (IOException e) {
                e.printStackTrace();
            }

Have to precise that CookieManager is from java.net.CookieManager;

0
public static void makeJsonObjectRequest(Context context, String url, final VolleyResponseListener listener) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error.toString());
            }
        }) {

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
           Map<String, String> responseHeaders = response.headers;
            String yourCookies = responseHeaders.get("Set-Cookie");
            Log.d("cookies",yourCookies);
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
};

// Access the RequestQueue through singleton class.
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
 }
Rakhi Dhavale
  • 1,196
  • 12
  • 19
  • I mentioned that the cookies are not in the header Set-Cookie :) so this method doesn't work. – Abderrahmane Kaci Aissa Apr 09 '19 at 12:13
  • @AbderrahmaneKaciAissa But cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client), isn't it ? – Rakhi Dhavale Apr 09 '19 at 12:26
  • 1
    As shown in my question, using postman, I receive the cookies in the cookies tab, meanwhile, I have no Cookies in the header, so I wonder how can I access to that cookies tab from java. – Abderrahmane Kaci Aissa Apr 09 '19 at 12:31
  • Can you post your code for making volley request in the question ? – Rakhi Dhavale Apr 09 '19 at 12:32
  • Actually, I was using the same code you gave me, but when I check for headers, not Set-Cookie header is present, so I assume that those cookies are not in the headers, now I am looking for a method to extract them, even if I need to change the library and not use volley, my issue is how to access that cookies part. – Abderrahmane Kaci Aissa Apr 09 '19 at 12:40
0

Actually If the request method is GET. Then might be the below example will work

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

URL url = new URL("url");

URLConnection connection = url.openConnection();
connection.getContent();

List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
    System.out.println(cookie.getDomain());
    System.out.println(cookie);
}
Soham
  • 4,397
  • 11
  • 43
  • 71
  • If possible can you provide me the api url and the request body,so I can try it on my end.@AbderrahmaneKaciAissa – Soham Apr 09 '19 at 13:55
0

When you make a call to your login api, most probably you are getting the cookie in first attempt and in the next ones you can not.

This is because cookie is already there but not on the headers anymore.

You might want to save the cookie in your first call and refresh it after some time according to your lifecycle requirements.

You can try and see this with Postman. It's a great tool for REST. Here is the link.

Another possible reason for that may be:

Cookie returns null or not the expected result when using volley library because when you call this:

response.headers.get("Set-Cookie");

Response headers are not mapped properly. Calling

response.headers

returns a Map object but it doesn't know the type. That's where it breaks. So a better approach would be to receive the Map object first properly like this:

Map<String, String> map = response.headers;

then:

String cookie = map.get("Set-Cookie");
Tahir Ferli
  • 636
  • 4
  • 16