user567 user567 - 19 days ago 17
Android Question

Set post params with volley

I am trying to send a POST request with volley but I am not sure how to set the params. I tried this code

Map<String,String> map = new HashMap<String,String>();
map.put("test", "test");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, String.valueOf(new JSONArray(map)), this, this);


The app crashes when this code is executed with the error


Activity com.example.test.MainActivity has leaked ServiceConnection

Answer

In order to add POST parameters to your request you need to override the getParams() and 2 other methods of Request class:

public class MapJARequest extends Request<JSONArray> {

  private final Map<String, String> params;

  private Response.Listener<JSONArray> listener;

  public MapJARequest( int method, String url, Map<String,String> params, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener ) {
    super( method, url, errorListener );
    this.params = params;
    this.listener = listener;
  }

  protected Map<String, String> getParams() throws AuthFailureError {
    return params;
  }

  @Override
  protected Response<JSONArray> parseNetworkResponse( NetworkResponse response ) {
    try{
      String jsonString = new String( response.data, HttpHeaderParser.parseCharset( response.headers ) );
      return Response.success( new JSONArray( jsonString ), HttpHeaderParser.parseCacheHeaders( response ) );
    }catch( Exception je ){
      return Response.error( new ParseError( je ) );
    }
  }

  @Override
  protected void deliverResponse( JSONArray response ) {
    listener.onResponse( response );
  }

}

Be aware that you can not inherit from JsonArrayRequest straight away unfortunately.