Android Question okHttp not handling cookies

Inman

Well-Known Member
Licensed User
Longtime User
Does OkHttp have any issue with saving and restoring cookies automatically? I am facing the following issue:

I have a Reddit client app which was working correctly. I hadn't updated it in over a year but due to some change in Reddit API I am forced to do so now. The app is working fine using HttpUtils and old HttpClient implementation. But when I tried to do it with okHttp (and okHttpUtils2), it does not look like it is saving the user login cookie. For example, after login to Reddit with API (which works and returns the hash and other value correctly), I immediately call the Subscribed API to get a list of subreddits the user is subscribed to. In my old app, it is still returning the correct values in JSON. But in okHttp version it returns an empty {}. I suspect this is because the API cannot detect the logged in user as the Subscribed API relies entirely on cookie to do that.

I saw a post on Stackoverflow which I think is related to this. A solution is also mentioned. Could you please take a look?

http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android

I am using the following:
  • B4A 6.31
  • okHttp 1.01
  • OkHttpUtils2 2.20
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Cookies are handled automatically. Are you sending the requests to the same domain?

The persistent cookie store deals with a different problem where you want to save the cookies to a file and later use them again.

Note that you can also manually fetch the cookies and add them to the next request. This can solve issues where the domain matching rules do not work as you expect.
You can get the cookies from the Set-Cookie header (in hc_ResponseSuccess) and add them to following requests by setting the Cookie header.
 
Upvote 0

Inman

Well-Known Member
Licensed User
Longtime User
Ok I will try to set the cookie manually like you said
I need to set the cookie immediately after requesting the download, right? Like below:
B4X:
job1.Initialize("Job1",Me)
job1.Download("https://www.reddit.com/subreddits/mine/subscriber.json?limit=100")
job1.GetRequest.SetHeader("Cookie","cookie values")
 
Upvote 0
Top