使用 header 和参数 Volley 删除请求
Delete Request With header and Parametes Volley
您好,我想使用 Volley 以及 Headers 和 body 参数向服务器发送删除请求。但我无法成功发送请求
我试过的
JSONObject jsonbObjj = new JSONObject();
try {
jsonbObjj.put("nombre", Integer.parseInt(no_of_addition
.getText().toString()));
jsonbObjj.put("cru", crue);
jsonbObjj.put("annee", 2010);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
VolleyRequest mVolleyRequest = new VolleyRequest(
Method.DELETE, url, jsonbObjj,
new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
// TODO Auto-generated method stub
if (pDialog != null) {
pDialog.dismiss();
}
Log.e("Server Response", "response = "
+ jsonObject.toString());
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
if (pDialog != null) {
pDialog.dismiss();
}
Log.e("Error Response",
"Error " + arg0.getMessage());
Log.e("Error Response",
"Error = " + arg0.getCause());
}
}, mUserSession.getUserEmail(), mUserSession
.getUserPassword(), false);
ApplicationController.getInstance().addToRequestQueue(
mVolleyRequest, "deleteRequest");
这是我的 VolleyRequest 请求 class
public class VolleyRequest extends JsonObjectRequest {
String email, pass;
boolean saveCookeis;
public VolleyRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener,
String email, String pass, boolean saveCookie) {
super(method, url, jsonRequest, listener, errorListener);
// TODO Auto-generated constructor stub
this.email = email;
this.pass = pass;
this.saveCookeis = saveCookie;
}
public VolleyRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(Method.POST, url, jsonRequest, listener, errorListener);
// TODO Auto-generated constructor stub
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// TODO Auto-generated method stub
HashMap<String, String> params = new HashMap<String, String>();
String auth = "";
try {
auth = android.util.Base64.encodeToString(
(this.email + ":" + this.pass).getBytes("UTF-8"),
android.util.Base64.DEFAULT);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params.put("Authorization", auth);
return params;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// TODO Auto-generated method stub
if (saveCookeis) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
ApplicationController.getInstance().checkSessionCookie(
response.headers);
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
return super.parseNetworkResponse(response);
}
}
当我尝试此代码时,我收到 400 响应代码错误请让我知道是否有人可以帮助我..我做错了什么。谢谢
这里是我测试过的删除 Api 的屏幕截图,它工作正常。
更新:
我已将我的工作示例项目发布到 GitHub 以修复 java.net.ProtocolException: DELETE does not support writing
,请查看。
您的应用收到 400
错误代码,因为数据主体尚未通过 DELETE
请求发送。
在 HurlStack.java 中,您会发现以下内容:
case Method.DELETE:
connection.setRequestMethod("DELETE");
break;
case Method.POST:
connection.setRequestMethod("POST");
addBodyIfExists(connection, request);
break;
所以我们可以看到 DELETE
请求忽略了正文数据。有一个解决方法,就是你创建一个CustomHurlStack
class(复制上面HurlStack
的所有内容),只修改如下:
case Request.Method.DELETE:
connection.setRequestMethod("DELETE");
addBodyIfExists(connection, request);
break;
然后,在您的 activity 中调用:
CustomHurlStack customHurlStack = new CustomHurlStack();
RequestQueue queue = Volley.newRequestQueue(this, customHurlStack);
请注意,此解决方法仅适用于 API21+(API20 我尚未测试)。从 API19- 开始,将抛出 java.net.ProtocolException: DELETE does not support writing
。
P/S:如果您的应用 compileSdkVersion 23
并且在创建 CustomHurlStack
class 时出现错误,请在 build.gradle
文件中添加 useLibrary 'org.apache.http.legacy'
。
希望对您有所帮助!
url = "http://httpbin.org/delete"; //example URL
//constructor class
public VolleyLoader(Context context) {
this.context = context;
queue = Volley.newRequestQueue(context);
}
public void deleteData(String idData, callback callback){
Uri uri = Uri.parse(URL+ idData).buildUpon()
.build();
StringRequest dr = new StringRequest(Request.Method.DELETE, uri.toString,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Toast.makeText($this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error.
}
}
);
queue.add(dr);
}
// use that method to delete data when web api only provide "id_data" to delete in header
您好,我想使用 Volley 以及 Headers 和 body 参数向服务器发送删除请求。但我无法成功发送请求
我试过的
JSONObject jsonbObjj = new JSONObject();
try {
jsonbObjj.put("nombre", Integer.parseInt(no_of_addition
.getText().toString()));
jsonbObjj.put("cru", crue);
jsonbObjj.put("annee", 2010);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
VolleyRequest mVolleyRequest = new VolleyRequest(
Method.DELETE, url, jsonbObjj,
new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
// TODO Auto-generated method stub
if (pDialog != null) {
pDialog.dismiss();
}
Log.e("Server Response", "response = "
+ jsonObject.toString());
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
if (pDialog != null) {
pDialog.dismiss();
}
Log.e("Error Response",
"Error " + arg0.getMessage());
Log.e("Error Response",
"Error = " + arg0.getCause());
}
}, mUserSession.getUserEmail(), mUserSession
.getUserPassword(), false);
ApplicationController.getInstance().addToRequestQueue(
mVolleyRequest, "deleteRequest");
这是我的 VolleyRequest 请求 class
public class VolleyRequest extends JsonObjectRequest {
String email, pass;
boolean saveCookeis;
public VolleyRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener,
String email, String pass, boolean saveCookie) {
super(method, url, jsonRequest, listener, errorListener);
// TODO Auto-generated constructor stub
this.email = email;
this.pass = pass;
this.saveCookeis = saveCookie;
}
public VolleyRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(Method.POST, url, jsonRequest, listener, errorListener);
// TODO Auto-generated constructor stub
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// TODO Auto-generated method stub
HashMap<String, String> params = new HashMap<String, String>();
String auth = "";
try {
auth = android.util.Base64.encodeToString(
(this.email + ":" + this.pass).getBytes("UTF-8"),
android.util.Base64.DEFAULT);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params.put("Authorization", auth);
return params;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// TODO Auto-generated method stub
if (saveCookeis) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
ApplicationController.getInstance().checkSessionCookie(
response.headers);
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
return super.parseNetworkResponse(response);
}
}
当我尝试此代码时,我收到 400 响应代码错误请让我知道是否有人可以帮助我..我做错了什么。谢谢
这里是我测试过的删除 Api 的屏幕截图,它工作正常。
更新:
我已将我的工作示例项目发布到 GitHub 以修复 java.net.ProtocolException: DELETE does not support writing
,请查看。
您的应用收到 400
错误代码,因为数据主体尚未通过 DELETE
请求发送。
在 HurlStack.java 中,您会发现以下内容:
case Method.DELETE:
connection.setRequestMethod("DELETE");
break;
case Method.POST:
connection.setRequestMethod("POST");
addBodyIfExists(connection, request);
break;
所以我们可以看到 DELETE
请求忽略了正文数据。有一个解决方法,就是你创建一个CustomHurlStack
class(复制上面HurlStack
的所有内容),只修改如下:
case Request.Method.DELETE:
connection.setRequestMethod("DELETE");
addBodyIfExists(connection, request);
break;
然后,在您的 activity 中调用:
CustomHurlStack customHurlStack = new CustomHurlStack();
RequestQueue queue = Volley.newRequestQueue(this, customHurlStack);
请注意,此解决方法仅适用于 API21+(API20 我尚未测试)。从 API19- 开始,将抛出 java.net.ProtocolException: DELETE does not support writing
。
P/S:如果您的应用 compileSdkVersion 23
并且在创建 CustomHurlStack
class 时出现错误,请在 build.gradle
文件中添加 useLibrary 'org.apache.http.legacy'
。
希望对您有所帮助!
url = "http://httpbin.org/delete"; //example URL
//constructor class
public VolleyLoader(Context context) {
this.context = context;
queue = Volley.newRequestQueue(context);
}
public void deleteData(String idData, callback callback){
Uri uri = Uri.parse(URL+ idData).buildUpon()
.build();
StringRequest dr = new StringRequest(Request.Method.DELETE, uri.toString,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Toast.makeText($this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error.
}
}
);
queue.add(dr);
}
// use that method to delete data when web api only provide "id_data" to delete in header