Search code examples
kotlinandroid-volleykotlin-android-extensionskotlin-extensionrx-kotlin

How to put header in url using volley in Kotlin?


My code-

val accessTokenRequest: JsonObjectRequest = JsonObjectRequest(Request.Method.GET, url,
            Response.Listener { response ->
            },
            Response.ErrorListener { error ->
                Toast.makeText(activity,error.toString(), Toast.LENGTH_LONG).show()
            }
    )

    AppController.instance!!.addToRequestQueue(accessTokenRequest)

Header I wat to put - "Search"& "Authorization"


Solution

  • Try using the following code to add headers

    val accessTokenRequest: JsonObjectRequest = object : JsonObjectRequest(
        Request.Method.GET, "", JSONObject(),
        Response.Listener<JSONObject?> {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }, Response.ErrorListener {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }) {
        @Throws(AuthFailureError::class)
        override fun getHeaders(): Map<String, String> {
            var params: MutableMap<String, String>? = super.getHeaders()
            if (params == null) params = HashMap()
            params["Authorization"] = "Your authorization"
            //..add other headers
            return params
        }
    }
    

    Note: To generate kotlin code from java try using Ctrl + Shift + Alt + K or simply copy paste it on a kotlin file.