我们如何在HashMap
中传递UrlEncodedFormEntity
参数?或者如何解决?
答案 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);