OkHTTP

Android initially provide two HTTP clients Apache HTTP Client and HttpURLConnection for receiving and sending data.

DrawBack of Apache HTTP Client and HttpURLConnection

  • Each of these clients required a lot of boilerplate code as it has to place inside the AsyncTask or Background Threads.
  • It becomes very complicated for cancelling an HTTP request or connection pooling.

OkHTTP

OKHttp API implements HttpURLConnection and Apache Client and works on the top of Java Socket. Hence we don’t need any extra dependencies.

Why OkHttp prefers over Apache HTTP Client and HttpURLConnection?

As it Easier to use and requires less steps as compare to Apache HTTP Client and HttpURLConnection and provides various like

  • Connection Pooling
  • Gziping
  • Caching
  • Recovering from network problems
  • Redirects
  • Retries
  • Support for synchronous and asynchronous calls

Synchronous vs Asynchronous calls
Synchronous calls require an AsyncTask wrapper around it. That means it doesn’t support cancelling a request. Also, AsyncTasks generally leak the Activity’s context, which is not preferred.

Asynchronous Calling is the recommended way since it supports native cancelling, tagging multiple requests and cancelling them all with a single method call (by invoking the cancel on the Activity instance inside the onPause or onDestroy method).

Refer for more details and codes

1) https://www.journaldev.com/13629/okhttp-android-example-tutorial

2) https://www.sitepoint.com/consuming-web-apis-in-android-with-okhttp/

 

 

 

 

 

Posted in Android.