2

I am quite new to Android app development and would like to perform a simple API request via HTTP to a web server. URL("http://www.myapi.com").readText() seems to be a good way to start with, but this leads to a NetworkOnMainThreadException. So it must run asynchronously or in a coroutine. However, I'm not familiar enough with this and other examples I have found so far don't work for me.

Thanks a lot already for your help!

2 Answers2

0

if you are using mvvm pattern you can do the following in your ViewModel class

viewModelScope.launch {val response = withContext(Dispatchers.IO) { your request }}
0

HTTP requests are no longer allowed by default on Android 9 and above. Consider using HTTPS, or modify the AndroidManifest.xml, see this answer on StackOverflow.

linuskmr
  • 727
  • 3
  • 13