Sending HTTP DELETE request in Android
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();}
getOutputStream() only works on requests that have a body, like POST. Using it on requests that don't have a body, like DELETE, will throw a ProtocolException. Instead, you should add your headers with addHeader() instead of calling getOutputStream().