Learning Android Development

OkHttp or Retrofit for Android?

Deciding which to pick when doing a project

Elye
Elye
Aug 26, 2020 · 4 min read

you work on networking in Android, you probably heard of OkHttp and Retrofit. They are not really totally different. In fact, Retrofit is just a higher-level API wrap around OkHttp within. So the questions are

  • What does Retrofit really provide on top of OkHttp?
  • Should we consider using OkHttp directly?

There several StackOverflow like this and this talk about them as well. Let me give you more detailed descriptions below.

What Retrofit provides on top of OkHttp

Structured URL and Parameter construction

In Retrofit, you construct your retrofit object by providing the BASE_URL.

Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()

Then in your service interface API, you have all the query parameter defined properly

@GET(BASE_PATH)
fun hitCountCheckCall(@Query(PARAM_ACTION) action: String,
@Query(PARAM_FORMAT) format: String,
@Query(PARAM_LIST) list: String,
@Query(PARAM_SRSEARCH) srsearch: String)
: Call<Model.Result>

And to make the network call, you just need to provide the value by passing it to the defined API

wikiApiServe.hitCountCheckCall(
VALUE_QUERY, VALUE_JSON, VALUE_SEARCH, searchString)

OkHttp

In OkHttp, you have to manually construct the request like below

val request = Request.Builder().url("$BASE_URL$BASE_PATH/?" +
"$PARAM_ACTION=$VALUE_QUERY&$PARAM_FORMAT=$VALUE_JSON&" +
"$PARAM_LIST=$VALUE_SEARCH&$PARAM_SRSEARCH=$searchString")
.build()

Result as Constructed Object instead of Raw e.g. JSON

In Retrofit, as you have provided the GSON Converter Factory to it, and you told your output object type e.g. Model.Result as below

@GET(BASE_PATH)
fun hitCountCheckCall(@Query(PARAM_ACTION) action: String,
@Query(PARAM_FORMAT) format: String,
@Query(PARAM_LIST) list: String,
@Query(PARAM_SRSEARCH) srsearch: String)
: Call<Model.Result>

Then upon return of result, you can use the response.body() directly.

call?.enqueue(
object : Callback<Model.Result> {
override fun onFailure(call: Call<Model.Result>, t: Throwable) {
// Do something with failure
}

override fun onResponse(call: Call<Model.Result>,
response: Response<Model.Result>) {
response.body()?.let { useResult(it) }
})

OkHttp

In OkHttp, you’ll need to deserialize the result yourselves.

client.newCall(request).enqueue(
object : okhttp3.Callback {
override fun onFailure(call: okhttp3.Call, e: IOException) {
// Do something with failure
}

override fun onResponse(call: okhttp3.Call,
response: okhttp3.Response) {
response.body()?.let {
val result = Gson().fromJson(it.string(),
Model.Result::class.java)
useResult(result)

}
}
)

Auto Bring Result to Main Thread

In Retrofit, if you use enqueue, it will put the network call to background automatically. And when the result is returned, it is automatically sent to the main UI thread. Hence you can do UI operation e.g. Toast.

override fun onResponse(call: Call<Model.Result>, 
response: Response<Model.Result>) {
Toast.makeText(...).show()
})

Of course, there are many background threading processes like RxJava, Coroutine that Retrofit support as well. Check out

OkHttp

In OkHttp, through the enqueueit will put the network call to background automatically. But when the result is returned, it will still be on the background thread.

Hence we need to use runOnUiThread before performing any UI Operation manually.

override fun onResponse(call: okhttp3.Call, 
response: okhttp3.Response) {
runOnUiThread {
Toast.makeText(...).show()
}
}

If we don’t do so, it will crash.

If you like to see other threading option for OkHttp, check out

These are the few things that Retrofit provides on top of OkHttp. It makes networking so much convenient. It can also use to download larger files etc, although for things like images you want to use Glide or Picasso or Coil, and for video you use ExcoPlayer.

Should we consider using OkHttp directly

From the above, it sounds like Retrofit pretty much cover everything we need, and simplifies things as well.

However, we know OkHttp is the base of Retrofit, hence for sure it does have some area where we should consider using it directly.

More Dynamic URL Formation

As shown above, the Retrofit does provide us a very structured URL formation for one to call. So in the case, the Base URL we have varies, then we’ll need to construct different Retrofit objects and also have the interface for the API formation. This though may be feasible, but might be complicating.

Using OkHttp directly might be simpler in this case, as we have the flexibility of forming the URL

Custom construction of network process

Retrofit upon return will usually form the object one retrieved using the Gson Factory constructor we provide it. Most things are defined, which means possible customization limited.

Underlying Retrofit, it is using Reflection. If we want to extend some class from it, might not be possible due to it is final by default. So if you want to have more control over your own network process, using OkHttp directly should provide you that flexibility.

Avoid delay in adopting the newer framework

When retrofit was introduced, it is using the enqueue as the API, and later get into RxJava. However, RxJava 2 libraries came out later, users who use Retrofit will have to wait for Retrofit to support before one can get onto.

Similarly of late coroutine is out, hence it will take a while for Retrofit to have that support ready. Hence reliance on Retrofit, one will have to wait for it to adopt to the newer framework before you can move on.

Note: Although OkHttp library comes with Retrofit, one can still set a newer version of OkHttp through its API.

That’s it. Hopes this clear out any confusion if one has on Retrofit and OkHttp. You can get the sample code from

Mobile App Development Publication

Sharing Mobile App Development and Learning

Elye

Written by

Elye

Passionate about learning, and sharing mobile development and others https://twitter.com/elye_project https://www.facebook.com/elye.proj

Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Elye

Written by

Elye

Passionate about learning, and sharing mobile development and others https://twitter.com/elye_project https://www.facebook.com/elye.proj

Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store