Android

Here Is The List Of Best Android Networking Libraries Or Dependencies

Today we list out some of the most famous Networking Libraries for building Android applications. These libraries are listed based on the number of downloads in descending order.

All you have to do sit back, take a Pepsi can and read some kickass code. Here is a list of top five Android Networking Libraries (Dependencies).

1. OkHttp (Http + Http /2)

Currently, OkHttp is the most used Http client library provided by the square.github.io community for Java and Android developers. Using OkHttp is easy. It supports both synchronous blocking calls and asynchronous calls with callbacks. OkHttp by default supports network catching under the hood for avoiding the repeat network request.

Note: OkHttp requires at minimum Android 5.0+ (API level 21+) and Java 8+.

Let’s see a simple example of download a URL and print its content.

OkHttp example of synchronous blocking Call

val client = OkHttpClient()

@Throws(IOException::class)
private fun getContent(url: String): String {
    val request: Request = Request.Builder()
            .url(url)
            .build()
    val response: Response = client.newCall(request).execute() // A blocking Synchronous call
    return response.body().toString()
}

fun main() {
    try {
          val content: String = getContent("www.google.com")
          println(content)
    } catch (e: IOException) {
          e.printStackTrace()  // handle error
    }
}

OkHttp example of asynchronous call with Callback

val client = OkHttpClient()

fun getRequest(url : String) : Request = Request.Builder()
       .url(url)
       .build()

fun main() {
    client.newCall(getRequest("www.google.com"))
          .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // handle IoException
                }

                override fun onResponse(call: Call, response: Response) {
                    val content = response.body().toString()
                    // handle downloaded content
                }
            })
}

OkHttp resource:

http://square.github.io/okhttp – OkHTTP Homepage

2. Retrofit

No doubt Retrofit is our favorite library when it comes to networking. Retrofit is an awesome type-safe HTTP client for Android and Java built by awesome folks at Square. It makes it easy to consume JSON or XML data which is parsed into Plain Old Java Objects (POJO’s). The Retrofit makes it so much easier to create Http request via annotations.

Let’s see an example of what I’m talking about:

interface ApiService {
   
   @GET(value = "user/{id}")  // retreive user with get request
   fun user(@Path(value = "id") userId : Long) : Call<User>

   @POST(value = "user")  // insert user with post request.
   fun user(@Body user : User) : Call<StatusMessageResponse>
}

// Building simple retrofit client 
val retrofit = Retrofit.Builder()
       .addConverterFactory(GsonConverterFactory.create())  // for parsing Json with Gson 
       .baseUrl("https://54.45.88.87:8080/api")  // Base url of your api requests
       .build()

// Create Http API for retrofit with simple Java interface  
val apiService = retrofit.create(ServiceUtil::class.java)

fun main() {
   val response : Response = apiService.user(10).execute()
   val user : User = response.body()
   // handle fetched user....

   val response : Response = apiService.user(User(id = 14, name = "Ahsen Saeed")).execute()
   val statusMessageResponse : StatusMessageResponse = resonse.body() 
   // handle inserted user response
}

You see there’s not much of a difference when executing network requests with Retrofit. It is the same as OkHttp, well that is because Retrofit internally used the OkHttp library.

Check out the StackOver Flow question -> Why use Retrofit when we’ve OkHttp

Note: Retrofit requires at minimum Java 7 or Android 2.3.

Retrofit resource:

http://square.github.io/retrofit/ – Retrofit Homepage

3. Ion (koush)

Ion is a simple but powerful HTTP networking library for Android. It features a Fluent Chainable API. Great for reusing connections, canceling requests taking too long, displaying images. Automatically cancels running operation when the calling Activity finishes. Asynchronously download images into ImageView (support animated Gif ).

The more than 6,000 Github users who starred this library can not be wrong!

Let’s see an example of downloading content from URL.

Download content with Ion from url as a String

Ion.with(context: this)
      .load("GET", "www.google.com")
      .asString()
      .setCallback { e, result ->
            e?.let { exception ->
                 exception.printStackTrace()
                    [email protected]
            }
            // handle result as string
      }

POST-Json as object and read Json

val response: Future<StatusMessageResponse> = Ion.with(this)
         .load("POST", "https://54.45.88.87:8080/api/user/")
         .setJsonPojoBody(user)
         .`as`(object : TypeToken<StatusMessageResponse>() {})  // returned response object
         .setCallback { e, response ->
              e?.let { exception ->
                  exception.printStackTrace()
                  [email protected]
              }
              // handle result as StatusMessageResponse
         }

        response.cancel()  //  for cancelling purpose

Download image with progressBar and load into an ImageView

Ion.with(this)
     .load("http://example.com/image.png")
     .progressBar(progressBar)
     .withBitmap()
     .intoImageView(imageView)
      .setCallback(object : FutureCallback<ImageView> {
            override fun onCompleted(e: Exception?, result: ImageView?) {
                    progressBar.visibility = View.GONE
             }
       })

Ion Resource

https://github.com/koush/ion Ion Koush Resource

4. AndroidAsync (Koush)

AndroidAsync is the second android networking library from Koush. It is a low-level network protocol library, lightweight, and very easy to implement for beginners. According to this library documentation:

If you’re looking for higher-level, Android aware, http request library use the Ion library which we’ve discussed earlier. But if you’re looking for a raw Socket, HTTP(s) client/server, and WebSocket library for Android, AndroidAsync is it.

Below is an example of how to use the library.

val getRequest = AsyncHttpGet("www.google.com")  // for get request 
val postRequest = AsyncHttpPost("https://54.45.88.87:8080/api/user/")  // for post request

AsyncHttpClient.getDefaultInstance()
                .executeString(getRequest, object : AsyncHttpClient.StringCallback() {
                override fun onCompleted(e: Exception?, source: AsyncHttpResponse?, result: String?) {
                    e?.let { exception ->
                        exception.printStackTrace()
                        return
                    }
                    // handle result as a String
                }
            })

AndroidAsync Resource

The rest of the important information you can find in README. There is also an example app.

Fast Android Networking Library

Yet! it is another android networking powerful library which made on top of OkHttp Networking. Here the list of advantages of using this library.

  • Support for RxJava
  • Response catching–Reduce bandwidth usage
  • Request canceling
  • Use OkHttp internally and also support HTTP/2
  • An executor can be passed to any request to get a response in another thread–Lift heavy task from the main thread.
  • Set priority for every request.

In order to use the Fast Android Networking library, first, initialize it in your onCreate() method of the application class.

class MyApplication : Application() {
 
    override fun onCreate() {
        super.onCreate()
        AndroidNetworking.initialize(applicationContext)
    }
 }

Executing a Get Request

AndroidNetworking.get("www.google.com")
            .setTag("uniqueTag")
            .build()
            .getAsString(object : StringRequestListener {
                override fun onResponse(response: String?) {
                    // handle response
                }

                override fun onError(anError: ANError?) {
                    // handle error
                }
            })

AndroidNetworking.cancel("uniqueTag") // cancel specific request with tag
AndroidNetworking.cancelAll()  // cancel all request

Post request by passing an object as Json and read Json

AndroidNetworking.post("https://54.45.88.87:8080/api/user/")
                 .addBodyParameter(user)
                 .build()
                 .getAsObject(StatusMessageResponse::class.java, object : ParsedRequestListener<StatusMessageResponse> {
                override fun onResponse(response: StatusMessageResponse?) {
                        // handle response
                }

                override fun onError(anError: ANError?) {
                      // handle error
                }
            })

More Resources

A description of the project is well-written and easy to read. Check out here.

That’s it. I hope you enjoyed the list of top Android Networking Client Libraries. If you like my article, please don’t forgot to click 💟 below. If you have any queries regarding this list or suggestion comment at the end of this article.

Thank you for being here and keep reading…

Write A Comment