Difference between RequestParams add() and put() in AndroidAsyncHttp
Asked Answered
M

1

7

While using the android-async-http library I stumbled upon params.add().

I've been using params.put() for a while and it seems better than add() since it allows data types other than String (like int, long, object, file) while add() does not.

RequestParams params = new RequestParams();

// So how is this
params.add("param_a", "abc");

// different from this
params.put("param_a", "abc");

// and which one should I use?
Maleficence answered 25/12, 2014 at 17:11 Comment(1)
Use add() for Arrays and put() for everything else.Groves
G
16

The major difference between the two (other than add()'s String-only support) is that put() overwrites the previous presence of param with an existing key while add() does not.

For example:

params.put("etc", "etc");
params.put("key", "abc");
params.put("key", "xyz");

// Params: etc=etc&key=xyz

While add creates two params with the same key:

params.add("etc", "etc");
params.add("key", "abc");
params.add("key", "xyz");

// Params: etc=etc&key=abc&key=xyz

But what is the importance of doing this?

In the above example, the web-server would only read the last value of key i.e. xyz and not abc but this is useful when POSTing arrays:

params.add("key[]", "a");
params.add("key[]", "b");
params.add("key[]", "c");

// Params: key[]=a&key[]=b&key[]=c
// The server will read it as: "key" => ["a", "b", "c"]
Groves answered 25/12, 2014 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.