Nguyen Thuan
Nguyen Thuan

Reputation: 361

How to add a custom header in a Volley request with Kotlin

I have some code. In Volley code:

 val queue = Volley.newRequestQueue(context)

 val stringRequest = StringRequest(
            Request.Method.GET,
            linkTrang,
            Response.Listener<String> { response ->
                mTextView.text = "Response is: " + response.substring(0, 500));
            },
            Response.ErrorListener { })
    {

    }
    queue.add(stringRequest)

How do I set a header called Authorization in this?

Upvotes: 6

Views: 11471

Answers (1)

Daniel Diehl
Daniel Diehl

Reputation: 752

I was able to do it in Kotlin using:

    val linkTrang = "YOUR URL"

    val queue = Volley.newRequestQueue(this)

    val stringRequest = object: StringRequest(Request.Method.GET, linkTrang,
        Response.Listener<String> { response ->
            Log.d("A", "Response is: " + response.substring(0,500))
        },
        Response.ErrorListener {  }) 
    {
        override fun getHeaders(): MutableMap<String, String> {
            val headers = HashMap<String, String>()
            headers["Authorization"] = "Basic <<YOUR BASE64 USER:PASS>>"
            return headers
        }
    }

    queue.add(stringRequest)

It is important to use the object keyword before the construction of the request in order to be able to override the getHeaders() method.

Upvotes: 42

Related Questions