Sending HTTP DELETE request in Android

androidneil picture androidneil · Apr 26, 2012 · Viewed 19.7k times · Source

My client's API specifies that to remove an object, a DELETE request must be sent, containing Json header data describing the content. Effectively it's the same call as adding an object, which is done via POST. This works fine, the guts of my code is below:

HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setUseCaches(false);
con.connect();
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(data); // data is the post data to send
wr.flush();

To send the delete request, I changed the request method to "DELETE" accordingly. However I get the following error:

java.net.ProtocolException: DELETE does not support writing

So, my question is, how do I send a DELETE request containing header data from Android? Am I missing the point - are you able to add header data to a DELETE request? Thanks.

Answer

TalkLittle picture TalkLittle · May 11, 2013

The problematic line is con.setDoOutput(true);. Removing that will fix the error.

You can add request headers to a DELETE, using addRequestProperty or setRequestProperty, but you cannot add a request body.