user2791100
user2791100

Reputation: 11

Android HttpClient DELETE method with request body

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?

Upvotes: 1

Views: 1653

Answers (2)

dube
dube

Reputation: 5019

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();

Upvotes: 2

marcus.ramsden
marcus.ramsden

Reputation: 2633

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);

Upvotes: 1

Related Questions