Search code examples
androidresthttpkotlin

HTTP Request in Android with 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.


Solution

  • For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

    However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

    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")
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                inputStream.bufferedReader().use {
                    it.lines().forEach { line ->
                        println(line)
                    }
                }
            } else {
                val reader: BufferedReader = inputStream.bufferedReader()
                var line: String? = reader.readLine()
                while (line != null) {
                    System.out.println(line)
                    line = reader.readLine()
                }
                reader.close()
            }
        }
    }
    

    Or simpler (though potentially less practical for very large sites):

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