To say in simple words i want to send this {"Id":7,"Name":"MyName"}
data To server using Volley Post Request.
It has 1 integer and 1 String and response i get is Jsonarray
I tried Following ways but none are working
as it is json array request i cannot send data in argument as 3rd argument only takes JsonArray and i have to send JsonObject so kept it as null
new JsonArrayRequest(Method,Url,JsonArray,ResponseListener,ErrorListner)
I cannot put it in HashMap
as 1 of the value is integer, and it only accepts string
getparams() method
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("Id",7); // <====== This is Invalid
params.put("Name","MyName");
return params;
}
getbody method
@Override
public byte[] getBody() {
String body="{\"Id\":7,\"Name\":\"MyName\"}";
return body.getBytes();
}
I can get the response using HttpUrlConnection.
Is there any other way to achieve it in volley ?
Thanks to akash93 , i finally did it .Here is how to do it
write a class MyJsonArrayRequest.java like below
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
public class MyJsonArrayRequest extends JsonRequest<JSONArray> {
public MyJsonArrayRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
usage :
MyJsonArrayRequest request=new MyJsonArrayRequest(Request.Method.POST, Constants.SEARCH_PROFILE, object, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.i("onResponse", ""+response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.i("onErrorResponse", "Error");
}
});
even more easier way is to override getBody()
which should work , but some way it didn't work for me first time.
@Override
public byte[] getBody() {
String body="{\"Id\":7,\"Name\":\"MyName\"}";
return body.getBytes();
}
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