Manually set the cookie in the default cookie and use it in okhttp requests

In my Android app, I switch to okhttp and you need to configure PHPSESSID manually for registered users in the default Store cookie so that they do not log out. I manually set the cookie using the following code.

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

It seems that the cookie is set because I can return the cookie using this code

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

However, when I make a client call using

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

Cookies are not sent in the request (this network call is confirmed using the android proxy).

What is the correct way to set such a cookie so that the okhttp client uses this cookie?

+4
1

, CookieHandler put CookieManager CookieStore add.

, put CookieManager, HttpCookie, . , CookieStore add, HttpCookie.

, OkHttp get , CookieManager, CookieStore . , get path cookie, .

"/" HttpCookie, cookie .

HttpCookie

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

, CookieHandler, CookieStore

:

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

All Articles