如何在Kotlin中的Volley请求中添加Url中的Body?

时间:2018-09-07 09:10:08

标签: json kotlin android-volley kotlin-android-extensions rx-kotlin

以下是我的排球请求代码:-

    val searchRequest = object : JsonArrayRequest(Request.Method.GET,url,
            Response.Listener { response ->

                val result = response.toString()


            },
            Response.ErrorListener { error ->
                Toast.makeText(activity, "Error!",Toast.LENGTH_LONG)
                        .show()
                Log.d("ERROR",error.toString())
            })
    {
        override fun getBody(): ByteArray {

           //   TODO add Body, Header section works  //////////

            return super.getBody()
        }

        override fun getBodyContentType(): String {
            return "application/json"
        }


        override fun getHeaders() : Map<String,String> {
            val params: MutableMap<String, String> = HashMap()
            params["Search-String"] = songName
            params["Authorization"] = "Bearer ${accessTx.text}"
            return params
        }
    }
    AppController.instance!!.addToRequestQueue(searchRequest)

我想在正文部分添加此信息

video_id =“ BDJIAH”, audio_quality =“ 256”

这是在以下细分中添加上述信息的示例。

{ “ video_id”:“ ABCDE”,  “ audio_quality”:“ 256” }

基本上,我在ByteArray部分遇到问题。那对我不起作用。

2 个答案:

答案 0 :(得分:3)

我创建此函数是为了向服务器发送呼叫,这就是您如何在呼叫中添加正文的方法。

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head> 

答案 1 :(得分:1)

在Kotlin中使用参数对排球发布请求

private fun loginUser() {
    val username: String = etName.getText().toString().trim()
    val password: String = etPass.getText().toString().trim()
    val stringRequest: StringRequest = object : StringRequest( Method.POST, LOGINURL,
        Response.Listener { response ->
            Toast.makeText(this, response, Toast.LENGTH_LONG).show()
            try {
                val jsonObject = JSONObject(response)
                //Parse your api responce here
                /*val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)*/
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        },
        Response.ErrorListener { error ->
            Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show()
        }) {
        override fun getParams(): Map<String, String> {
            val params: MutableMap<String, String> = HashMap()
            //Change with your post params
            params["username"] = username
            params["password"] = password
            return params
        }
    }
    val requestQueue = Volley.newRequestQueue(this)
    requestQueue.add(stringRequest)
}