Difference between RequestParams add() and put() in AndroidAsyncHttp

泪湿孤枕 提交于 2020-01-11 08:30:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!