1. Add this dependency in your gradle fie
implementation 'com.android.volley:volley:1.1.0'
2. Volley Get Method
fun getVolley(){
// Instantiate the Volley RequestQueue.
val queue = Volley.newRequestQueue(this)
val url: String = "PUT_YOUR_URL"
// Request a string response from the URL
val stringReq = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
var str_res = response.toString()
Log.d("API", str_res)
},
Response.ErrorListener { error ->
Log.d("API GET ERROR", "get error => $error") })
queue.add(stringReq)
}
3. Volley Post Method
fun postVolley() {val queue = Volley.newRequestQueue(this)val url = "https://reqres.in/api/users"//PUT YOUR BODY IN STRAING WITH JSON KEY NAME/*Want to post this data{name:"mijas",job:"Youtuber"}*/val requestBody = "name=Mijas" + "&job=Youtuber"val stringReq : StringRequest =object : StringRequest(Method.POST, url,Response.Listener { response ->// responsevar str_res = response.toString()Log.d("API Response", str_res)},Response.ErrorListener { error ->Log.d("API POST ERROR", "post error => $error")}){override fun getBody(): ByteArray {return requestBody.toByteArray(Charset.defaultCharset())}}queue.add(stringReq)}
No comments:
Post a Comment