Skip to content Skip to sidebar Skip to footer

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 ->

Solution 1:

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

funsendcall() {
            //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()
            }) {
                overridefungetBodyContentType(): String {
                    return"application/json"
                }

                @Throws(AuthFailureError::class)overridefungetBody(): ByteArray {
                    val params2 = HashMap<String, String>()
                    params2.put("Login","your credentials" )
                    params2.put("Password", "your credentials")
                    return JSONObject(params2).toString().toByteArray()
                }

            }
            mRequestQueue!!.add(mStringRequest!!)
        }

Solution 2:

Volley post request in kotlin with params

privatefunloginUser() {
    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()
        }) {
        overridefungetParams(): 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)
}

Post a Comment for "How To Add Body In Url In Volley Request In Kotlin?"