12

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?

pratsJ
  • 3,369
  • 3
  • 22
  • 41

1 Answers1

20

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.

Community
  • 1
  • 1
Phileo99
  • 5,581
  • 2
  • 46
  • 54
  • 2
    For completeness sake, the rest of the docs: "Otherwise the two cache instances will stomp on each other, corrupt the response cache, and possibly crash your program." – Mauker Mar 19 '16 at 02:50
  • What if I am not interested in caching at all? – RScottCarson Jan 02 '18 at 22:42