Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. But as being new its quiet confusing for most of us.
One of the confusion is setting parameters in volley requests. The paramenters can be set in a volley request by overriding getParams() method of Request<T> class. But the problem is that the getParams() is called only in the case of POST or PUT request. As the documentation says:
1 2 3 4 5 6 7 |
Returns a Map of parameters to be used for a POST or PUT request. Can throw {@link AuthFailureError} as authentication may be required to provide these values. Note that you can directly override {@link #getBody()} for custom data. @throws AuthFailureError in the event of auth failure |
But what in case of GET method!!
In case of GET method the paraments are concatenated with the url and then url is passed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
StringRequest strreq = new StringRequest(Request.Method.GET, "http://196.1.1.1/myurl?param1=" + num1 + "¶m2=" + num2, new Response.Listener<String>() { @Override public void onResponse(String Response) { // get response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError e) { e.printStackTrace(); } }); Volley.getInstance(this).addToRequestQueue(strreq); |
Its quiet easier approach but it becomes a lot of work when you have a lot of parameters then you have to concatenate each and every paramenter in the url. In GET request the getParams() is not even called so there is no way you can use the methods
In case of POST method you can override the getParams() and give all the parameters you want over there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
StringRequest strreq = new StringRequest(Request.Method.POST, "http://196.1.1.1/myurl", new Response.Listener<String>() { @Override public void onResponse(String Response) { // get response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError e) { e.printStackTrace(); } }){@Override public Map<String, String> getParams(){ Map<String, String> params = new HashMap<>(); params.put("param1", num1); params.put("param2", num2); return mParams; } }; Volley.getInstance(this).addToRequestQueue(strreq); |
Also for JSONobjectRequest the getParams() doen’t even work for POST request so you have to make a customRequest and override getParams() method over there. Its because JsonObjectRequest is extended JsonRequest which override getBody() method directly, so your getParam() would never invoke. To invoke your getParams() method you first have to override getBody(). Or for a simple solution you can use StringRequest.