« Network calls without Retrofit
Here we are using HttpURLConnection and Gson serializer.
1CoroutineScope(Dispatchers.IO).launch {2 var httpURLConnection: HttpURLConnection? = null3 try {45 val url = URL("https://reqres.in/api/users?page=2")67 httpURLConnection = url.openConnection() as HttpURLConnection89 val code = httpURLConnection.responseCode1011 if (code != 200) {12 throw IOException("The error from the server is $code")13 }1415 val bufferedReader = BufferedReader(16 InputStreamReader(httpURLConnection.inputStream)17 )1819 val jsonStringHolder: StringBuilder = StringBuilder()2021 while (true) {22 val readLine = bufferedReader.readLine() ?: break23 jsonStringHolder.append(readLine)24 }2526 val userProfileResponse =27 Gson().fromJson(jsonStringHolder.toString(), UserProfileResponse::class.java)2829 withContext(Dispatchers.Main) {30 findViewById<TextView>(R.id.name).apply {31 text = userProfileResponse.data[0].let {32 "${it.firstName} ${it.lastName}"33 }34 }35 }36 } catch (ioexception: IOException) {37 Log.e(this.javaClass.name, ioexception.message.toString())38 } finally {39 httpURLConnection?.disconnect()40 }41}
For full code repository please refer