0

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

4

1 回答 1

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);
于 2012-05-30T07:36:45.763 回答