Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volley - POST/GET parameters

I saw Google IO 2013 session about Volley and I'm considering switching to volley. Does Volley support adding POST/GET parameters to request? If yes, how can I do it?

like image 432
Ziem Avatar asked May 18 '13 15:05

Ziem


1 Answers

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",                            num1,                            num2);  StringRequest myReq = new StringRequest(Method.GET,                                         uri,                                         createMyReqSuccessListener(),                                         createMyReqErrorListener()); queue.add(myReq); 

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,                                         "http://somesite.com/some_endpoint.php",                                         createMyReqSuccessListener(),                                         createMyReqErrorListener()) {      protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {         Map<String, String> params = new HashMap<String, String>();         params.put("param1", num1);         params.put("param2", num2);         return params;     }; }; queue.add(myReq); 

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

like image 115
Ognyan Avatar answered Sep 19 '22 12:09

Ognyan