使用标题和Parametes Volley删除请求

时间:2015-11-05 19:51:55

标签: android android-volley sql-delete jsonobject

您好我想使用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请求类

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的屏幕截图,它的工作正常。

I need to send this Data to server

And here is the response form server

2 个答案:

答案 0 :(得分:6)

<强>更新

我已将我的工作示例项目发布到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类(复制上面HurlStack的所有内容),只修改如下:

            case Request.Method.DELETE:
                connection.setRequestMethod("DELETE");
                addBodyIfExists(connection, request);
                break;

然后,在您的活动中,请致电:

CustomHurlStack customHurlStack = new CustomHurlStack();
RequestQueue queue = Volley.newRequestQueue(this, customHurlStack);

请注意,此解决方法仅适用于API21 +(API20我尚未测试)。从API19-开始,java.net.ProtocolException: DELETE does not support writing将被抛出。

P / S:如果您的应用useLibrary 'org.apache.http.legacy',则在build.gradle文件中添加compileSdkVersion 23,并在创建CustomHurlStack课程时收到错误。

希望这有帮助!

答案 1 :(得分:0)

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