我需要发送一个带有重复参数名称的POST请求,例如“param = a& param = b”。
覆盖Request.getParams()不起作用,因为Map不能有重复的键,所以只发送一个值。
我知道我可以重写Request类来使用Map或Map>但是如果有任何其他方法不需要更改库,我就会徘徊。
提前致谢。
PS:我在排球用户组中提出了同样的问题:https://groups.google.com/forum/#!topic/volley-users/tFRclnEbpAk
答案 0 :(得分:3)
Ficus Kirkpatrick回答了我关于排球用户组的问题 (https://groups.google.com/d/msg/volley-users/tFRclnEbpAk/uiC2f9nAIgkJ):
您可以覆盖getBody()而无需修改库。
˚F
所以我创建了以下帮助器类:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpParams extends HashMap<String, List<String>> {
private static final long serialVersionUID = 1L;
public HttpParams() {
super();
}
public HttpParams(int capacity) {
super(capacity);
}
public HttpParams(Map<String, List<String>> map) {
super(map);
}
public HttpParams(int capacity, float loadFactor) {
super(capacity, loadFactor);
}
/*
* This is the method to use for adding post parameters
*/
public void add(String key, String value) {
if (containsKey(key)) {
get(key).add(value);
}
else {
ArrayList<String> list = new ArrayList<String>();
list.add(value);
put(key, list);
}
}
/**
* Converts the Map into an application/x-www-form-urlencoded encoded string.
*/
public byte[] encodeParameters(String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, List<String>> entry : entrySet()) {
String key = URLEncoder.encode(entry.getKey(), paramsEncoding);
for (String value : entry.getValue()) {
encodedParams.append(key);
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(value, paramsEncoding));
encodedParams.append('&');
}
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
}
然后在我的类中扩展Request I覆盖了getBody():
@Override
public byte[] getBody() throws AuthFailureError {
if (mParams != null && mParams.size() > 0) {
return mParams.encodeParameters(getParamsEncoding());
}
return null;
}
答案 1 :(得分:0)
Map确实不支持重复但是你支持重复 可以做这样的事情。你不必重写getBody(),只是我假设你已经在做的getParams。
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();;
params.putAll(AddArrayParams());
return params;
}
public Map<? extends String, ? extends String> AddArrayParams() {
Map<String, String> params = new HashMap<String, String>();
// figure that if its an array and the data is sent as [0],[1] then lets just send it up that way
params.put("param[0]","a");
params.put("param[1]","b");
params.put("param[3]","c");
////etc
return params;
}
祝你好运