Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Volley Request with Body

Is it possible to send a simple text in the body of a StringRequest using DELETE-Method?

I couldn't find any example where somebody put something in the body of a request... This is my request and I want to add "{'deviceid':'xyz'}" to the body (method is DELETE):

final StringRequest stringRequest = new StringRequest(method, url + "?token=" + token, new Response.Listener<String>() {
        @Override
        public void onResponse(String jsonResponse) {
            // do something
    }, new Response.ErrorListener() {
            // do something
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("api-version", "1");

            return headers;
        }
    };
like image 312
Unknown User Avatar asked Mar 15 '23 21:03

Unknown User


2 Answers

This because Volley doesn't send the Body for DELETE by default. Only for POST, PUT and PATCH. Unfortunate to say the least

There is a workaround for it listed here: Volley - how to send DELETE request parameters?

like image 105
Chris Avatar answered Mar 28 '23 08:03

Chris


Try this:

public class StringJSONBodyReqest extends StringRequest {

    private static final String TAG = StringJSONBodyReqest.class.getName();
    private final String mContent;

    public StringJSONBodyReqest(int method, String url, String content, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
        mContent = content;
    }


    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("api-version", "1");

        return headers;
    }


    @Override
    public byte[] getBody() throws AuthFailureError {

        byte[] body = new byte[0];
        try {
            body = mContent.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Unable to gets bytes from JSON", e.fillInStackTrace());
        }
        return body;
    }


    @Override
    public String getBodyContentType() {
        return "application/json";
    }
}

mContent is your json String

like image 43
dieter_h Avatar answered Mar 28 '23 06:03

dieter_h