Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually set a cookie in default cookiestore and using it in okhttp requests

In my android application, I am migrating to okhttp and need to setup the PHPSESSID manually for logged-in users in the default cookieStore, so that they don't get logged out. I am manually setting the cookie using the following code.

((CookieManager)client.getCookieHandler()).getCookieStore().add(new URI("http://www.example.com"), new HttpCookie("PHPSESSID", getPhpSessionID()));

The cookie seems to be set cause I can get the cookie back using this code

((CookieManager)client.getCookieHandler()).getCookieStore().get(new URI("http://www.example.com"));

However, when I am executing the client call using

Request request = new Request.Builder().url("http://www.example.com/getdata.php").build(); 
client.newCall(request).execute();

The cookies are not being sent in the request (verified this network call using android proxy).

Whats the correct way to set such a cookie so that okhttp client uses that cookie?

like image 503
Udbhav Avatar asked Sep 23 '14 20:09

Udbhav


1 Answers

There seem to be a difference between the CookieHandler's put implementation of the CookieManager and the CookieStore's add method.

By default if you use the put from the CookieManager it will add the domain and the path to the HttpCookie created internally by the implementation. This will not happen if you use the CookieStore's add method directly as you're the one responsible for creating the HttpCookie.

As it turns out OkHttp uses the get from the implementation which in your case will be CookieManager and not the CookieStore directly. That get will also use the path to match the cookie which in your case will be missing.

If you don't provide the expected default path of "/" to your HttpCookie your cookie will not be found.

You should then modify your HttpCookie like so

HttpCookie cookie = new HttpCookie("PHPSESSID", getPhpSessionID());
cookie.setPath("/");
cookie.setVersion(0);
cookie.setDomain("www.example.com");
((CookieManager)client.getCookieHandler()).getCookieStore().add(new URI("http://www.example.com"), cookie);

Or to allow your solution to be more adaptable in the chance that you change CookieHandler implementation you could use the interface only instead of getting access to the CookieStore

You would accomplish this like so

List<String> values = new ArrayList<>(Arrays.asList("PHPSESSID=" + "your_session_id_here"));
Map<String, List<String>> cookies = new HashMap<>();
cookies.put("Set-Cookie", values);
client.getCookieHandler().put(new URI("http://www.example.com"), cookies);
like image 173
Miguel Avatar answered Oct 19 '22 22:10

Miguel