6

Hi i want to Send Delete Request to server using Volley along Headers and body parameters. but i am not able to send request successfully

What i have tried

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");

and here is my VolleyRequest request 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);

    }

}

When i tried this code i get 400 response code error Please let me know if anyone can help me.. that what i am doing wrong. Thanks

here the screen shots for Delete Api which i tested and its working fine.

I need to send this Data to server

And here is the response form server

Mustanser Iqbal
  • 5,017
  • 4
  • 18
  • 36
  • Hi! Since I don't have working credentials (user, pass) so the response code I got with your server url is 500, not 400 :) – BNK Nov 05 '15 at 22:22
  • I think you can try with `params.put("Authorization", "Basic " + auth);` – BNK Nov 06 '15 at 01:28
  • its not working with params. and m getting 400 while send request from application but it works well when i hit URL from browser.. my user name is specified in image and pass is 1234 if you can check please check it and tell me what m doing wrong. Thanks – Mustanser Iqbal Nov 06 '15 at 05:02
  • I think your code is not wrong. It is not working only because body ignored in DELETE request. You can find in HurlStack.java `case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break;`. Read some solution here http://stackoverflow.com/questions/19050706/android-volley-delete-method-why-will-send-empty-parameters – BNK Nov 06 '15 at 06:51
  • okay let me check and then i'll let you know. anyway Thanks – Mustanser Iqbal Nov 06 '15 at 07:27
  • actually m too much busy with another project as i check i'll inform you. i'll check it on tonight or tomorrow. – Mustanser Iqbal Nov 07 '15 at 09:06

2 Answers2

10

UPDATE:

I have posted my working sample project to GitHub to fix java.net.ProtocolException: DELETE does not support writing, please take a look.


Your app got 400 error code because the data body has not been sent with DELETE request.

Inside HurlStack.java, you will find the following:

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

So we can see DELETE request ignores body data. There's a workaround, that is you create a CustomHurlStack class (copy all content of HurlStack above), with only modification as the following:

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

Then, in your activity, call:

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

Please note that this workaround works only for API21+ (API20 I have not tested). From API19-, java.net.ProtocolException: DELETE does not support writing will be thrown.

P/S: add useLibrary 'org.apache.http.legacy' inside your build.gradle file if your app compileSdkVersion 23 and you get error when create CustomHurlStack class.

Hope this helps!

BNK
  • 23,994
  • 8
  • 77
  • 87
  • can you please tell how can i create newRequestQueue method like here http://stackoverflow.com/a/30748487/3593066http://stackoverflow.com/a/30748487/3593066. m little confused please explain because i am getting this error java.net.ProtocolException: DELETE does not support writing – Mustanser Iqbal Nov 08 '15 at 05:00
  • 1
    If you have control over server-side app (web service), I suggest you change so that DELETE request uses URL parameters instead of body params – BNK Nov 08 '15 at 05:49
  • that is the main problem... i dont have access to web service – Mustanser Iqbal Nov 08 '15 at 06:44
  • 1
    I uploaded my new sample project to https://github.com/ngocchung/DeleteRequest, please take a look. However, because the last success run got the response `I/onResponse: {"reste":0}`, so other requests later will get `response code 400` because there's no item to delete :). Actually, they will get `{ "error": "bad request", "message": "suppression impossible : pas assez de bouteilles correspondantes en cave" }` – BNK Nov 09 '15 at 02:31
  • 2
    Thanks man its working perfectly. and thanks one again for your time. (y) – Mustanser Iqbal Nov 09 '15 at 09:30
  • Glad it could help, happy coding :) – BNK Nov 09 '15 at 10:04
  • can you give me some idea how to achieve this animation http://gettipsi.com/static/landing/landing2/images/Wine_Scanning_Animation.gif?68 (scanning animation) currently m doing this with the help of animation list defined in anim. – Mustanser Iqbal Nov 09 '15 at 11:56
  • Sorry, I am not familiar with animation in Android :) – BNK Nov 10 '15 at 04:47
  • i need a little help. please – Mustanser Iqbal Dec 08 '15 at 10:46
  • Yes, however I am on mobile, so I don't know can help you much or not – BNK Dec 08 '15 at 13:51
  • actuall i am using volley in an other project to send JsonObject. but i dont know what this error mean.. can you tell me what that mean {{{12-08 23:06:44.546 29293-29293/com.pilot E/onErrorResponse: org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject}}} i can show code how i am trying if you like... thanks – Mustanser Iqbal Dec 08 '15 at 17:41
  • 1
    Thanks Brother for your consideration. i have solved it. actually i parse the network response with UTF-8 and it work. Thanku – Mustanser Iqbal Dec 08 '15 at 18:53
  • Ok Bro :), sometimes if the server responses compressed (zip) data, you should decompress it at parseNetworkResponse too. – BNK Dec 08 '15 at 23:49
  • Thanks, i don't why client don't access to web api. they give the link and said request on this URL. that's it create problem sometimes.. anyway thanks – Mustanser Iqbal Dec 09 '15 at 04:31
  • Brother do you have any experience with retrofit? I need a little help in this please. – Mustanser Iqbal Dec 13 '15 at 18:17
  • Not much, I have tried it only 2-3 times before, however, if you have any issue, pls create a new question, IMO, many people in SO can help :) – BNK Dec 14 '15 at 01:06
  • please have a look at this question http://stackoverflow.com/q/36309092/3593066 Thanks – Mustanser Iqbal Mar 30 '16 at 12:44
  • Please read http://stackoverflow.com/questions/32240177/working-post-multipart-request-with-volley-and-without-httpentity to see if it can help or not. – BNK Mar 30 '16 at 13:06
  • i am getting socket timeOut exception. i am updating my today's question. what i have trying to do. please check. – Mustanser Iqbal Mar 30 '16 at 16:01
  • HttpClient is removed since SKD 23. Any workaround for that solution, or considering updating your git? – Kevin Flachsmann Mar 13 '17 at 22:47
  • @KevinFlachsmann pls read http://stackoverflow.com/questions/32472263/apache-http-client-removal-from-api23-will-that-have-an-effect-on-volley – BNK Mar 14 '17 at 01:09
  • it was helpful me rather making custom hurl stack i appended params in url – Abdul Waheed Jun 13 '17 at 09:55
  • @BNK Hi i checked your answer and sample , it does not work for me , it is giving me same Error DELETE does not support Writing Protocol exception. – Anshu P Aug 09 '17 at 04:51
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