Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple HTTP request example in Android using Kotlin

I am new to Android development with Kotlin and I am struggling on finding any useful documentation on how to create a simple GET and POST requests with the best current practices as possible. I am coming from an Angular development and there we used a reactive development using RxJS.

Normally I would create a service file that would hold all my request functions, then I would use this service in whichever component and subscribe to the observable.

How would you do this in Android? Is there a good started example of things that have to be created. From the first look, everything looks so complicated and over-engineered

like image 575
Gregor A Avatar asked Aug 02 '26 13:08

Gregor A


2 Answers

I suggest you to use the official recommendation of OkHttp, or the Fuel library for easier side and it also has bindings for deserialization of response into objects using popular Json / ProtoBuf libraries.

Fuel example:

// Coroutines way:
// both are equivalent
val (request, response, result) = Fuel.get("https://httpbin.org/ip").awaitStringResponseResult()
val (request, response, result) = "https://httpbin.org/ip".httpGet().awaitStringResponseResult()

// process the response further:
result.fold(
    { data -> println(data) /* "{"origin":"127.0.0.1"}" */ },
    { error -> println("An error of type ${error.exception} happened: ${error.message}") }
)

// Or coroutines way + no callback style:
try {
    println(Fuel.get("https://httpbin.org/ip").awaitString()) // "{"origin":"127.0.0.1"}"
} catch(exception: Exception) {
    println("A network request exception was thrown: ${exception.message}")
}

// Or non-coroutine way / callback style:
val httpAsync = "https://httpbin.org/get"
    .httpGet()
    .responseString { request, response, result ->
        when (result) {
            is Result.Failure -> {
                val ex = result.getException()
                println(ex)
            }
            is Result.Success -> {
                val data = result.get()
                println(data)
            }
        }
    }

httpAsync.join()

OkHttp example:

val request = Request.Builder()
    .url("http://publicobject.com/helloworld.txt")
    .build()

// Coroutines not supported directly, use the basic Callback way:
client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        e.printStackTrace()
    }

    override fun onResponse(call: Call, response: Response) {
        response.use {
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            for ((name, value) in response.headers) {
                println("$name: $value")
            }

            println(response.body!!.string())
        }
    }
})
like image 184
Animesh Sahu Avatar answered Aug 07 '26 03:08

Animesh Sahu


you can use something like that:

internal inner class RequestTask : AsyncTask<String?, String?, String?>() {
         override fun doInBackground(vararg params: String?): String? {
            val httpclient: HttpClient = DefaultHttpClient()
            val response: HttpResponse
            var responseString: String? = null
            try {
                response = httpclient.execute(HttpGet(uri[0]))
                val statusLine = response.statusLine
                if (statusLine.statusCode == HttpStatus.SC_OK) {
                    val out = ByteArrayOutputStream()
                    response.entity.writeTo(out)
                    responseString = out.toString()
                    out.close()
                } else {
                    //Closes the connection.
                    response.entity.content.close()
                    throw IOException(statusLine.reasonPhrase)
                }
            } catch (e: ClientProtocolException) {
                //TODO Handle problems..
            } catch (e: IOException) {
                //TODO Handle problems..
            }
            return responseString
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            //Do anything with response..
        }
    }

and for call:

        RequestTask().execute("https://v6.exchangerate-api.com/v6/")

HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

If you need sdk 23, add this to your gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

You also may try to download and include HttpClient.jar directly into your project or use OkHttp instead

like image 37
Hassan Yousefzadeh Avatar answered Aug 07 '26 05:08

Hassan Yousefzadeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!