I am trying to fire a DELETE request using HttpUrlConnection in android,I am setting the setRequestmethod as DELETE and getting a 200 as response code. The Item is not getting deleted. The async I am using is below.
private class DeleteTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = null;
URL url = null;
try {
url = new URL(urls[0]);
Log.i("URL to access :", urls[0]);
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setUseCaches(false);
System.out.println("ResponseCode: "+httpURLConnection.getResponseCode());
if(httpURLConnection.getResponseCode() == 204){
Log.d(TAG,"Deleted");
}
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return null;
}
}
}
It looks like the setRequestMethod() is not working and its taking the Request as a GET and giving me a 200 !!
I tested this in postman(a chrome extension) and it was working fine , If it was a backend issue then from postman also it should fail.
okHttp:
I was trying to make this work on okHttp also for that
Request request = new Request.Builder().url(url.toString()).patch(body).build();
How will I make up this for delete, because delete request dosent have a body
Volly: I've tried out the google volly library too..
RequestQueue requestQueue = Volley.newRequestQueue(TimerSummary.this);
StringRequest request = new StringRequest(Request.Method.DELETE, uri, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG,"Response: "+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,"Error: "+error);
}
});
requestQueue.add(request);
This also returns like GET request, I am getting the item as json which was supposed to be deleted.
any suggestions are appreciated. Thanks in advance..
It was actually a typo!!! I am an idiot!Both of my methods work fine ,but I am Now using Google's volly library for network related things.
I was missing a "/" before the "?" before appending parameters with the URL