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 alread
Using only the standard library with minimal code!
thread {
val jsonStr = try { URL(url).readText() } catch (ex: Exception) { return@thread }
runOnUiThread { displayOrWhatever(jsonStr) }
}
This starts a GET request on a new thread, leaving the UI thread to respond to user input. However, we can only modify UI elements from the main/UI thread, so we actually need a runOnUiThread
block to show the result to our user. This enqueues our display code to be run on the UI thread soon.
The try/catch is there so your app won't crash if you make a request with your phone's internet off. Add your own error handling (e.g. showing a Toast) as you please.
.readText()
is not part of the java.net.URL
class but a Kotlin extension method, Kotlin "glues" this method onto URL
. This is enough for plain GET requests, but for more control and POST requests you need something like the Fuel library.