Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set RequestBody for Http Delete method.

I am writing a client code for a server which Delete API. The API specification requires data to be sent. I am using HttpComponents v3.1 library for writing client code. Using the HtpDelete class I could not find a way to add request data to it. Is there a way to do so ? Below is the code snippet.

        HttpDelete deleteReq = new HttpDelete(uriBuilder.toString());
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new BasicNameValuePair(RestConstants.POST_DATA_PARAM_NAME, 
            postData.toString()));
    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
        entity.setContentEncoding(HTTP.UTF_8);
        //deleteReq.setEntity(entity); // There is no method setEntity()
        deleteReq.setHeader(RestConstants.CONTENT_TYPE_HEADER, RestConstants.CONTENT_TYPE_HEADER_VAL);
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException: " + e);
    }

Thanks in advance.

like image 462
Tushar Tarkas Avatar asked Apr 10 '12 17:04

Tushar Tarkas


People also ask

Can we have request body for delete?

Yes it is allowed to include a body on DELETE requests, but it's semantically meaningless. What this really means is that issuing a DELETE request with a request body is semantically equivalent to not including a request body.


2 Answers

why not do this :-)

class MyHttpDelete extends HttpPost{
    @Override
    public String getMethod() {
        return "DELETE";
    }
}
like image 131
Ishan Liyanage Avatar answered Oct 11 '22 13:10

Ishan Liyanage


I haven't tried this, and it is as hackish as hell and I wolud feel happier if it turns out there is better solution, but you might try to extend PostMetod and override getName() method to return "DELETE".

like image 27
Slartibartfast Avatar answered Oct 11 '22 14:10

Slartibartfast