Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTTP DELETE request in Android

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.

like image 709
androidneil Avatar asked Apr 26 '12 17:04

androidneil


Video Answer


2 Answers

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.

like image 134
TalkLittle Avatar answered Sep 18 '22 04:09

TalkLittle


This is a limitation of HttpURLConnection, on old Android versions (<=4.4).

While you could alternatively use HttpClient, I don't recommend it as it's an old library with several issues that was removed from Android 6.

I would recommend using a new recent library like OkHttp:

OkHttpClient client = new OkHttpClient(); Request.Builder builder = new Request.Builder()     .url(getYourURL())     .delete(RequestBody.create(         MediaType.parse("application/json; charset=utf-8"), getYourJSONBody()));  Request request = builder.build();  try {     Response response = client.newCall(request).execute();     String string = response.body().string();     // TODO use your response } catch (IOException e) {     e.printStackTrace(); } 
like image 22
Murphy Avatar answered Sep 19 '22 04:09

Murphy