问题
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?
回答1:
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"]
来源:https://stackoverflow.com/questions/27649251/difference-between-requestparams-add-and-put-in-androidasynchttp