Hi, the kotlin code does a rest call to the backend but when I run the code I have an error on the urlConnection.connect () line, the error is the code below, how do I fix this?
Error:
android.os.NetworkOnMainThreadException
2021-05-07 16:01:18.792 24813-24813/com.app.xx W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
2021-05-07 16:01:18.792 24813-24813/com.app.xx W/System.err: at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
2021-05-07 16:01:18.792 24813-24813/com.app.xx W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
2021-05-07 16:01:18.792 24813-24813/com.app.xx W/System.err: at jav
Code:
fun getToken(ID_AUTH_FIREBASE:String,UTENTE:String,ADMIN_KEY:String ): String {
val dta = StringBuilder()
try {
// Creating & connection Connection with url and required Header.
val url = URL("http://url")
val urlConnection: HttpsURLConnection = url.openConnection() as HttpsURLConnection
urlConnection.setRequestProperty("Content-Type", "application/json")
urlConnection.requestMethod = "POST" //POST or GET
urlConnection.connect()
// Create JSONObject Request
val jsonRequest = JSONObject()
jsonRequest.put("ID_AUTH_FIREBASE", ID_AUTH_FIREBASE)
jsonRequest.put("UTENTE", UTENTE)
jsonRequest.put("ADMIN_KEY", ADMIN_KEY)
// Write Request to output stream to server.
val out = OutputStreamWriter(urlConnection.getOutputStream())
out.write(jsonRequest.toString())
out.close()
// Check the connection status.
val statusCode: Int = urlConnection.getResponseCode()
val statusMsg: String = urlConnection.getResponseMessage()
// Connection success. Proceed to fetch the response.
if (statusCode == 200) {
val it: InputStream = BufferedInputStream(urlConnection.getInputStream())
val read = InputStreamReader(it)
val buff = BufferedReader(read)
var chunks: String=""
while (buff.readLine().also({ chunks = it }) != null) {
dta.append(chunks)
}
System.out.println("Valore: "+dta.toString())
return dta.toString()
} else {
//Handle else case
}
} catch (e: Exception) {
System.out.println("Errore: "+e)
System.out.println(e.printStackTrace())
}
return dta.toString()
}