我尝试使用Volley向我的服务器发送DELETE类型请求并向请求添加参数。到目前为止,我还没有能够这样做。
创建自定义请求并覆盖getParams()方法对我没有帮助,因为不会为DELETE类型请求调用此方法。
如何在Volley中为DELETE请求添加参数?
答案 0 :(得分:12)
这里的问题相同,但我找到了解决方案。
问题是com.android.volley.toolbox.HttpClientStack.java中createHttpRequest方法的实现,只有在请求方法是POST,PUT或PATCH时才会添加正文。
/**
* Creates the appropriate subclass of HttpUriRequest for passed in request.
*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST: {
// This is the deprecated way that needs to be handled for backwards compatibility.
// If the request's post body is null, then the assumption is that the request is
// GET. Otherwise, it is assumed that the request is a POST.
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Method.GET:
return new HttpGet(request.getUrl());
case Method.DELETE:
return new HttpDelete(request.getUrl());
case Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Method.HEAD:
return new HttpHead(request.getUrl());
case Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Method.TRACE:
return new HttpTrace(request.getUrl());
case Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
所以你必须使用自己的HttpStack.java实现,或者重写HttpClientStack类。
首先,您应该从
替换RequestQueue的初始化RequestQueue requestQueue = Volley.newRequestQueue(sContext);
到
String userAgent = "volley/0";
try {
String packageName = getContext().getPackageName();
PackageInfo info = getContext().getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (PackageManager.NameNotFoundException e) {}
HttpStack httpStack = new OwnHttpClientStack(AndroidHttpClient.newInstance(userAgent));
RequestQueue requesQueue = Volley.newRequestQueue(sContext, httpStack);
并编写自己的HttpClientStack实现,在createHttpRequest()方法中更改“Method.POST:”的大小写。您还必须创建一个像“OwnHttpDelete”这样的对象作为HttpEntityEnclosingRequestBase的扩展,以使用方法setEntityIfNonEmptyBody()。
public class OwnHttpClientStack extends com.android.volley.toolbox.HttpClientStack {
private final static String HEADER_CONTENT_TYPE = "Content-Type";
public OwnHttpClientStack(HttpClient client) {
super(client);
}
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
addHeaders(httpRequest, additionalHeaders);
addHeaders(httpRequest, request.getHeaders());
onPrepareRequest(httpRequest);
HttpParams httpParams = httpRequest.getParams();
int timeoutMs = request.getTimeoutMs();
// TODO: Reevaluate this connection timeout based on more wide-scale
// data collection and possibly different for wifi vs. 3G.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
return mClient.execute(httpRequest);
}
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) {
for (String key : headers.keySet()) {
httpRequest.setHeader(key, headers.get(key));
}
}
static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Request.Method.DEPRECATED_GET_OR_POST: {
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Request.Method.GET:
return new HttpGet(request.getUrl());
case Request.Method.DELETE:
OwnHttpDelete deleteRequest = new OwnHttpDelete(request.getUrl());
deleteRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(deleteRequest, request);
return deleteRequest;
case Request.Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Request.Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Request.Method.HEAD:
return new HttpHead(request.getUrl());
case Request.Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Request.Method.TRACE:
return new HttpTrace(request.getUrl());
case Request.Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private static class OwnHttpDelete extends HttpPost {
public static final String METHOD_NAME = "DELETE";
public OwnHttpDelete() {
super();
}
public OwnHttpDelete(URI uri) {
super(uri);
}
public OwnHttpDelete(String uri) {
super(uri);
}
public String getMethod() {
return METHOD_NAME;
}
}
}
我希望我的代码可以帮助某人。还应该可以向HEAD请求添加参数。
答案 1 :(得分:2)
经过一些阅读和一些挖掘Volley的代码之后,我得出的结论是,在Volley中没有将参数附加到DELETE请求的方式 - 很可能是一种设计选择,因为它似乎总体上不受欢迎。
我想知道如何操作,因为我想将API密钥附加到我发送到服务器的每种类型的请求中。
如果有人发现自己有类似的问题,那么我最终做的事情(而且我现在很确定这就是这里的方法)是在标题部分发送API密钥请求。特别是在Volley中,这意味着重写getHeaders()方法并添加你需要的参数。
这是我的代码:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("API_KEY", apiKey);
return headers;
}