1

I'm attempting to use an HttpClient DELETE method in order to delete an item from a list.I want to send the relevant item_id using request body.I am using the following way in order to send the data.

 DefaultHttpClient httpclient = new DefaultHttpClient();
                httpclient = HttpUtils.getNewHttpClient();
                HttpDelete httpPostRequest = new HttpDelete(URL);     

                **httpPostRequest.setHeader("item_id",id);**
                httpPostRequest.addHeader("Authorization", getB64Auth(username,password));
                httpPostRequest.setHeader("Accept", "application/json");
                httpPostRequest.setHeader("Content-type", "application/json");
                httpPostRequest.setHeader("Accept-Encoding", "gzip"); 

But i am unable to delete the item into the server database. How to user Request body in HttpDelete?

2 Answers2

2

According to the Spec of HTTP/1.1 you cannot send a entity body with anything but POST and PUT.

Use a request parameter or an header attribute. You can use the URI Builder:

URI myURI = android.net.Uri.Builder.path(myPathString).query("item_id=1").build();
dube
  • 4,898
  • 2
  • 23
  • 41
  • Builder(myPathString) is undefined – user2791100 Jan 13 '14 at 13:26
  • Sorry to be a pedant but the HTTP/1.1 spec only specifically forbids a body entity on a TRACE request. Granted the DELETE method states, "The DELETE method requests that the origin server delete the resource identified by the Request-URI.", but everything else can have a body entity. – marcus.ramsden Jan 13 '14 at 13:38
  • @user2791100 you're right, fixed that. However, you need to look at the API to choose the right method, depending on your input (could be a full URL, a path, encoded/unencoded, ...) – dube Jan 13 '14 at 14:32
  • @marcus.ramsden you are right, newer versions of the spec explicitly allow a body-entity on DELETE. However, it should be noted that several servers and framework (probably mostly older versions) tend to dislike/ignore the body-entity on DELETE requests. – dube Jan 13 '14 at 14:37
1

Based on the answer over here that should give you a DELETE request with an entity field. Once you've made your own request type you could then do;

List<NameValuePair> deleteParams = new ArrayList<>();
deleteParams.add(new BasicNameValuePair("item_id", id));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(deleteParams);

HttpDeleteWithBody deleteRequest = new HttpDeleteWithBody(URL);
deleteRequest.addHeader("Authorization", getB64Auth(username,password));
deleteRequest.setHeader("Accept", "application/json");
deleteRequest.setHeader("Content-type", "application/json");
deleteRequest.setHeader("Accept-Encoding", "gzip"); 
deleteRequest.setEntity(entity);
Community
  • 1
  • 1
marcus.ramsden
  • 2,633
  • 1
  • 22
  • 33