我们如何在UrlEncodedFormEntity中传递HashMap参数..?

时间:2012-05-30 07:30:57

标签: java android

我们如何在HashMap中传递UrlEncodedFormEntity参数?或者如何解决?

1 个答案:

答案 0 :(得分:3)

我认为你的意思是这样的:

HashMap<String, String> values = ....;
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : values.entrySet()) {
    parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);

编辑#2:

如果您的HashMap拥有任意值,请记住这样做:

HashMap<String, Object> map = ....; // Your map goes here
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, ?> entry : map.entrySet()) {
    Object value = entry.getValue();
    if (value instanceof Collection) {
        Collection<?> values = (Collection<?>) value;
        for (Object v : values) {
            // This will add a parameter for each value in the Collection/List
            parameters.add(new BasicNameValuePair(entry.getKey(), v == null ? null : String.valueOf(v)));
        }
    } else {
        parameters.add(new BasicNameValuePair(entry.getKey(), value == null ? null : String.valueOf(value));
    }
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);