TransWikia.com

http url connection with kotlin on android

Code Review Asked on December 29, 2020

I’m making an http call from an android app and want to have it reviewed for brevity and efficiency. It handles both success and error streams, by contract 200 OK is enforced (not 201 created other codes etc.)

class UserNetwork() {

    fun findAll(): ArrayList<User>? {
        val url = URL("http:///10.0.2.2:8080/employees")
        val connection = url.openConnection() as HttpURLConnection
        connection.setRequestProperty("Accept", "application/json");

        var users: ArrayList<User>? = null

        (if (connection.responseCode == 200) connection.inputStream else connection.errorStream).use { stream ->
            BufferedReader(InputStreamReader(stream)).use { reader ->
                val response = StringBuffer()
                users = arrayListOf()

                @Suppress("ControlFlowWithEmptyBody")
                while ((reader.readLine().also { response.append(it) }) != null) {}

                val body = JSONArray(response.toString())
                for (i in 0 until body.length()) {
                    users?.add(User(body.getJSONObject(i)))
                }
            }
        }

        return users
    }
}

User data object.

data class User(var id: Long? = null, var first: String? = null, var last: String? = null): Parcelable {

    constructor(data: JSONObject) : this() {
        id = data.getLong("id")
        first = data.getString("first")
        last = data.getString("last")
    }
}

Test class (testing method for findAll)

class UserNetworkTest {
    @Test
    fun testFindAll() {
        val users = userProxy.findAll()
        assertEquals(3, users!!.size)
        users.forEach { user ->
            assertNotNull(user.id)
            assertNotNull(user.first)
            assertNotNull(user.last)
        }
    }
}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP