I have always read that data comes from server in json format also when we want to send some data we send to the server in json format so data travels in json format then where string request comes from? I dont know if we can post and get data in string format also, and what is the difference and use cases for using string and json requests?
Thanks!
A canned request for retrieving the response body at a given URL as a String.
JsonArrayRequest : A request for retrieving a JSONArray response body at a given URL. JsonObjectRequest : A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.
StringRequest class will be used to fetch any kind of string data. The response can be json, xml, html,text.
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
If you are expecting json object in the response, you should use JsonObjectRequest .
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
URL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
It's about the return type from the request, StringRequest
handles a String
as response like error = false
and JSONObjectRequest
handles a JSONObject
response like {"error" : false}
, how to know it's JSONObject
? with the usage of brackets ({
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With