Android Http Requests in Kotlin with OkHttp

Rohan Jahagirdar
4 min readMay 14, 2018

--

I am an Android Developer and have been developing apps for around 4 years now. Android development has been a great ride so far. I started with Android in the beginning of my career, hence it’s always held a close place in my heart. So when Google announced Kotlin as an official language for Android Development and the assurance of first class support for the language, it was an interesting thing.

I wouldn’t say I knew in depth of Kotlin before the announcement, and wouldn’t say I know a great deal about it even now. I’m still learning, but have enjoyed the experience so far. I was naturally intrigued with what Kotlin had to offer and most importantly how could I use the power that Kotlin provided.

Any Android developer who has used any kind of HTTP requests knows the efforts it takes to make sure that the entire process runs smoothly without any Exceptions or Crashes. Queuing requests, making them asynchronously, parsing the response and doing all this without breaking the app in any way or causing any crashes takes a while. A beginners start to Android App development quickly leads to creating an App that makes requests and connects to the world. When it comes to making requests very few libraries are as good as OkHttp. OkHttp has been widely used, tested and relied upon. Almost every App I have built for the last few years has used OkHttp. Having used Volley, OkHttp I felt is a gift of Gods with good documentation, high reliability and having light wieght.

I was recently trying to learn Kotlin and had decided to make an Android App using Kotlin as I feel doing a project is the best way to learn a language. The app called Out Of Eden is a personal project I decided to do after having learnt about the 21000 miles long walk by National Geographic’s Paul Salopek to traverse the path walked by the first humans in their migration from Africa to over the world.

When it came to making requests, OkHttp was my go to option. I wanted to use OkHttp for it. But there wasn’t much of help. So I decided to write a wrapper around the library. Using the wrapper made requests very easy and effortless with Kotlin. Following is my short work at it.

To get include the latest version of OkHttp in your app’s gradle file.

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

Sync the project to download the library.

Once that is done, I developed a Kotlin class file, called OkHttpRequest. This class is used to make requests and to parse response. It requires the OkHttpClient. This client is created in the Activity/Fragment using this class and passed to it. This client object is passed to the OkHttpRequest class and an object of the OkHttpRequest class is created. In out MainActivity.kt we create the client object and pass it to initialize an instance of the OKHttpRequest class.

var client = OkHttpClient()
var request = OkHttpRequest(client)

The MainActivity class has to implement the FetchCompleteListener interface.

class MainActivity : AppCompatActivity(), FetchCompleteListener {
...
}

Inside the OkHttpRequest class, there is there are 2 functions-POST and GET. We can add more, but for a basic project this should suffice. The GET function in the OKHttpRequest class:

fun GET(url: String, callback: Callback): Call {
val request = Request.Builder()
.url(url)
.build()

val call = client.newCall(request)
call.enqueue(callback)
return call
}

And the POST function in the OkHttpRequest class:

fun POST(url: String, parameters: HashMap<String, String>, callback: Callback): Call {
val builder = FormBody.Builder()
val it = parameters.entries.iterator()
while (it.hasNext()) {
val pair = it.next() as Map.Entry<*, *>
builder.add(pair.key.toString(), pair.value.toString())
}

val formBody = builder.build()
val request = Request.Builder()
.url(url)
.post(formBody)
.build()


val call = client.newCall(request)
call.enqueue(callback)
return call
}

We also have a companion object with the OkHttpRequest class. This specifies the MediaType.

companion object {
val JSON = MediaType.parse("application/json; charset=utf-8")
}

Now, once we have the OKHttpRequest class ready, we can go ahead and use it.

In our MainActivity.kt we can use the request object created to make requests by calling the POST or GET function.

val url = http://api.plos.org/search?q=title:%22Drosophila%22%20and%20body:%22RNA%22&fl=id,abstract&wt=json&indent=on

request.GET(url, object: Callback {
override fun onResponse(call: Call?, response: Response) {
val responseData = response.body()?.string()
runOnUiThread{
try
{
var json = JSONObject(responseData)
println("Request Successful!!")
println(json)
val responseObject = json.getJSONObject("response")
val docs = json.getJSONArray("docs")
this@MainActivity.fetchComplete()
} catch (e: JSONException) {
e.printStackTrace()
}
}
}

override fun onFailure(call: Call?, e: IOException?) {
println("Request Failure.")
}
})

That is a GET request done!

Now for the POST request, here is an implementation of it:

val url = "www.rohanjahagirdar.me"
val map: HashMap<String, String> = hashMapOf("fistNname" to "Rohan", "lastName" to "Jahagirdar", "profession" to "Student")
request.POST(url, map, object: Callback {
override fun onResponse(call: Call?, response: Response) {
val responseData = response.body()?.string()
runOnUiThread{
try
{
var json = JSONObject(responseData)
println("Request Successful!!")
this@MainActivity.fetchComplete()
} catch (e: JSONException) {
e.printStackTrace()
}
}
}

override fun onFailure(call: Call?, e: IOException?) {
println("Request Failure.")
}
})

And that is it. For a detailed use of the class, please have a look at the Out Of Eden Project. This is my first Medium post, and first blog post to actually! Would love to know your thoughts.

Thank you.

Rohan

--

--