Pass headers with Volley – Android kotlin

In the Android Volley library, you can pass headers with an HTTP request using Kotlin. Headers are used to pass additional information. Following will be the code to pass headers with the Volley library:

val queue = Volley.newRequestQueue(this)
val url = "http://172.20.10.4:3000/getUser"

val requestBody = ""
val stringReq: StringRequest =
    object : StringRequest(
        Method.POST, url,
        Response.Listener { response ->

            Log.i("mylog", response)

        },
        Response.ErrorListener { error ->
            Log.i("mylog", "error = " + error)
        }
    ) {
        override fun getHeaders(): MutableMap<String, String> {
            val headers = HashMap<String, String>()
            headers["Authorization"] = "Bearer {your_access_token}"
            return headers
        }

        override fun getBody(): ByteArray {
            return requestBody.toByteArray(Charset.defaultCharset())
        }
    }
queue.add(stringReq)

If you want to see how you can handle headers in the backend in Node JS, you are free to check our GitHub repo.