Android Volley With GET and POST Parameters Example

Posted / Публикувана 2013-05-28 in category / в категория: Android

Just added a simple example how to use GET and POST parameters to the Android Volley Examples project. You can find it under "GET and POST parameters" button.

Basically the example is quite simple: there is activity with two EditText fields used to enter a number and two buttons "Request with GET params" and "Request with POST params". You have to enter some digits in the fields, press one of the buttons and the request will be send to the server containing the parameters. Server will add the two numbers and return the sum which will be displayed bellow the buttons.

1. Request with GET parameters

In order to send request with GET parameters there are two alternatives:

1.1. To embed them directly in the string of the URL (as shown in the example) like:

String uri = String.format("http://ave.bolyartech.com/params.php?param1=%1$s¶m2=%2$s",
                           num1,
                           num2);
StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

In the code above num1 and num2 hold the parameters' values.

1.2. If you are using Volley with with external HttpClient (4.2.x) you can use URIBuilder in order to build the URI in more convenient way

 

2. Request with POST parameters

You will need override getParams() method of the request and return a Map<String, String> that holds your parameters and their values like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://ave.bolyartech.com/params.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);

 

getpost

2 Responses to “Android Volley With GET and POST Parameters Example”

  1. Can Says:

    Hi,

    How can use setEntity(new StringEntity) in Android Volley? We are doing this in normal way by this method HttpPost.setEntity(). But is there a way of using in Volley? I'd like to use it for Twitter like below.

    httpPost.setEntity(new StringEntity("grant_type=client_credentials"));

  2. Sam Says:

    Hey did you ever figure out how to use Volley with Twitter?

    I\'m also trying to setEntity with my request