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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With