Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android correct way to use OKHTTP singleton for parallel queries with cookies

I am working on an android project in which I am planning to replace Apache httpclient implementation with OKHTTP client. I would like to know how I can create a global Client that can be used for networking requests in different activities and services that will use the multi-threading of client. Should I create a singleton object of OKHTTPClient and reuse it in my code?

Also, where should I add the cookiestore to the request, In the global definition of client so that I all requests will have cookie available or while forming the request in individual activity or service?

like image 381
pratsJ Avatar asked Sep 15 '14 16:09

pratsJ


1 Answers

The general approach to using OkHttp is one OkHttp instance with one HttpResponseCache instance. Whether it needs to be created as a singleton depends on the requirements of your application. For example, the single instance of OkHttp can be created in a subclass of Android's Application.onCreate(), in which case it doesn't need to be a singleton if you make your Android app's subclass of the Application class a singleton.

Quote from their wiki:

"Most applications should call new OkHttp() exactly once, configure it with their cache, and use that same instance everywhere. "

Once you have created your OkHttp instance, you can use their setCookieHandler() API method to add a persistent cookie store, which will be used in all subsequent HTTP requests. See this SO answer for further details on implementing a cookiestore that works with OkHttp.

like image 105
Phileo99 Avatar answered Nov 18 '22 07:11

Phileo99