Wednesday 27 January 2016

android - HTTP Request in Kotlin



I'm completely new to Kotlin. I want to do a login validation using POST method and to get some information using GET method. I've URL, server Username and Password already of my previous project. I didn't find any proper example project which uses this thing. Anyone please suggest me any working example where I can use GET and POST method in HTTP request


Answer



For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client.



However, you can use standard libraries you would use in Java. For example, with HttpURLConnection you can do:



fun sendGet() {
val url = URL("http://www.google.com/")

with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET

println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

inputStream.bufferedReader().use {
it.lines().forEach { line ->
println(line)
}
}
}
}


Or simpler:



URL("https://google.com").readText()

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...