I am sending http request with kotlin and getting this error
Error: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx/xxx.android.ui.xxx}: android.os.NetworkOnMainThreadException
Additional info: GET request needs to work first. Because the process proceeds according to the response from the URL.
My Code:
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme_MainActivity)
super.onCreate(savedInstanceState)
val request = Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
}
}
Android main components, like
Activities,BroadcastReceiveretc, are running in the Main Thread. You can't make a network request (or another potentially long running operation) in the Main Thread. You need to schedule it in the background(worker) thread. By usingCall.execute()method you synchronously send the request. i.e. in the Main Thread. You can use methodCall.enqueue()to asynchronously send the request:There is also another approach of making and handling the request, using Kotlin Coroutines: