How to add a custom header in a Volley request with Kotlin
Asked Answered
A

1

6

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?

Athalia answered 13/8, 2018 at 9:27 Comment(3)
Possible duplicate of How to set custom header in Volley RequestQuit
I need a kotlin codeAthalia
Just copy/paste the Java code, you would get your Kotlin code.Dejesus
U
42

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.

Unpack answered 4/11, 2018 at 14:43 Comment(3)
Up vote for "It is important to use the object keyword "Attalanta
Nice way to use object keyword. Save my day. Thanks.Coldshoulder
Thank you man, you just saved my life! The object keyword is very important.Notability

© 2022 - 2024 — McMap. All rights reserved.