Delete Request With header and Parametes Volley
Asked Answered
U

2

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

Ultrasonic answered 5/11, 2015 at 19:51 Comment(6)
Hi! Since I don't have working credentials (user, pass) so the response code I got with your server url is 500, not 400 :)Pernod
I think you can try with params.put("Authorization", "Basic " + auth);Pernod
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. ThanksUltrasonic
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 #19051206Pernod
okay let me check and then i'll let you know. anyway ThanksUltrasonic
actually m too much busy with another project as i check i'll inform you. i'll check it on tonight or tomorrow.Ultrasonic
P
11

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!

Pernod answered 6/11, 2015 at 7:37 Comment(23)
can you please tell how can i create newRequestQueue method like here https://mcmap.net/q/1197575/-android-volley-delete-method-why-will-send-empty-parametershttp://stackoverflow.com/a/…. m little confused please explain because i am getting this error java.net.ProtocolException: DELETE does not support writingUltrasonic
If you have control over server-side app (web service), I suggest you change so that DELETE request uses URL parameters instead of body paramsPernod
that is the main problem... i dont have access to web serviceUltrasonic
I uploaded my new sample project to 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" }Pernod
Thanks man its working perfectly. and thanks one again for your time. (y)Ultrasonic
Glad it could help, happy coding :)Pernod
can you give me some idea how to achieve this animation gettipsi.com/static/landing/landing2/images/… (scanning animation) currently m doing this with the help of animation list defined in anim.Ultrasonic
Sorry, I am not familiar with animation in Android :)Pernod
i need a little help. pleaseUltrasonic
Yes, however I am on mobile, so I don't know can help you much or notPernod
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... thanksUltrasonic
Thanks Brother for your consideration. i have solved it. actually i parse the network response with UTF-8 and it work. ThankuUltrasonic
Ok Bro :), sometimes if the server responses compressed (zip) data, you should decompress it at parseNetworkResponse too.Pernod
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 thanksUltrasonic
Brother do you have any experience with retrofit? I need a little help in this please.Ultrasonic
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 :)Pernod
please have a look at this question https://mcmap.net/q/1771155/-upload-video-of-more-than-2mb-using-multi-part-request-android/3593066 ThanksUltrasonic
Please read #32240677 to see if it can help or not.Pernod
i am getting socket timeOut exception. i am updating my today's question. what i have trying to do. please check.Ultrasonic
HttpClient is removed since SKD 23. Any workaround for that solution, or considering updating your git?Hernadez
@KevinFlachsmann pls read #32472763Pernod
it was helpful me rather making custom hurl stack i appended params in urlRestrain
@Pernod 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.Conjoint
T
1
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  
Tavish answered 4/4, 2021 at 14:42 Comment(1)
use interface class to help transfer.....example: <code public interface callback { void onSuccessful(String result); // change your output base your data in web api void onFailed(String error); } >Tavish

© 2022 - 2024 — McMap. All rights reserved.