Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

post - How do you add an authorization to the header of a Volley JsonObjectRequest using Kotlin

I have looked at Java implementations of doing a POST using a JsonObjectRequest. I converted it to Kotlin but Android Studio throws up an error as soon as I add a body to the function (the curly brackets around the getHeaders function).

        // Request a string response from the provided URL.
        val jsonObjectRequest = JsonObjectRequest(        // Error here
            Request.Method.POST, url, postData,
            Response.Listener<JSONObject> {
                fun onResponse(response: JSONObject) {
                    println(response)
                }
            },
            Response.ErrorListener {
                fun onErrorResponse(error: VolleyError) {
                    error.printStackTrace()
                }
            })
        {                                                // Error caused by this open bracket
            @Override
            fun getHeaders() {
                val credentials = consumerkey+":"+consumersecret
                val headers: HashMap<String, String> = HashMap()
                val auth: String = Base64.encodeToString(credentials.toByteArray(), Base64.NO_WRAP)
                headers.put("Authorization", "Basic $auth")
            }
        }

The error shown by Android Studio when I hover the mouse over 'JsonObjectRequest' is this:

None of the following functions can be called with the arguments supplied.  <init>(Int, String!, JSONObject?, ((response: JSONObject!) → Unit)!, ((error: VolleyError!) → Unit)?) defined in com.android.volley.toolbox.JsonObjectRequest
<init>(Int, String!, JSONObject?, Response.Listener<JSONObject!>!, Response.ErrorListener?) defined in com.android.volley.toolbox.JsonObjectRequest
<init>(String!, JSONObject?, ((response: JSONObject!) → Unit)!, ((error: VolleyError!) → Unit)?) defined in com.android.volley.toolbox.JsonObjectRequest
<init>(String!, JSONObject?, Response.Listener<JSONObject!>!, Response.ErrorListener?) defined in com.android.volley.toolbox.JsonObjectRequest

What do I need to do to fix this or is there another way to add an authorisation to the header?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...