简体   繁体   中英

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

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())
        }
    }
})

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

The best practice you ever get to just go through the basics of networking call and create some demo applications using Android Studio.

If you want to click start then follow this tutorial

Simplet netwroking call in Kotlin

https://www.androidhire.com/retrofit-tutorial-in-kotlin/

Also, I would like to suggest Please create some demo application for GET and POST request and then merge these examples into your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM