Search code examples
jsonkotlinandroid-volleykotlin-android-extensionsrx-kotlin

How to add Body in Url in Volley request in Kotlin?


Here is my Code that for Volley Request:-

    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)

I want to add this information in the body section

video_id = "BDJIAH" , audio_quality = "256"

here is the sample to add above information in the below segment.

{ "video_id":"ABCDE", "audio_quality":"256" }

Basically, I am facing problem in ByteArray section. That doesn't work for me.


Solution

  • This function i created to send a call to server and this is how you will add body in your call.

        fun sendcall() {
                //RequestQueue initialized
                mRequestQueue = Volley.newRequestQueue(this)
    
               //String Request initialized
                mStringRequest = object : StringRequest(Request.Method.POST, url, Response.Listener { response ->
                    Toast.makeText(applicationContext, "Logged In Successfully", Toast.LENGTH_SHORT).show()
    
    
                }, Response.ErrorListener { error ->
                    Log.i("This is the error", "Error :" + error.toString())
                    Toast.makeText(applicationContext, "Please make sure you enter correct password and username", Toast.LENGTH_SHORT).show()
                }) {
                    override fun getBodyContentType(): String {
                        return "application/json"
                    }
    
                    @Throws(AuthFailureError::class)
                    override fun getBody(): ByteArray {
                        val params2 = HashMap<String, String>()
                        params2.put("Login","your credentials" )
                        params2.put("Password", "your credentials")
                        return JSONObject(params2).toString().toByteArray()
                    }
    
                }
                mRequestQueue!!.add(mStringRequest!!)
            }