How to add custom header in volley request with kotlin

拜拜、爱过 提交于 2021-01-01 08:14:52

问题


I have a code 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??


回答1:


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.



来源:https://stackoverflow.com/questions/51819176/how-to-add-custom-header-in-volley-request-with-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!