« Network calls without Retrofit

Here we are using HttpURLConnection and Gson serializer.

1CoroutineScope(Dispatchers.IO).launch {
2 var httpURLConnection: HttpURLConnection? = null
3 try {
4
5 val url = URL("https://reqres.in/api/users?page=2")
6
7 httpURLConnection = url.openConnection() as HttpURLConnection
8
9 val code = httpURLConnection.responseCode
10
11 if (code != 200) {
12 throw IOException("The error from the server is $code")
13 }
14
15 val bufferedReader = BufferedReader(
16 InputStreamReader(httpURLConnection.inputStream)
17 )
18
19 val jsonStringHolder: StringBuilder = StringBuilder()
20
21 while (true) {
22 val readLine = bufferedReader.readLine() ?: break
23 jsonStringHolder.append(readLine)
24 }
25
26 val userProfileResponse =
27 Gson().fromJson(jsonStringHolder.toString(), UserProfileResponse::class.java)
28
29 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

https://github.com/anishakd4/NetworkCallsWithoutRetrofit