I need to make a HTTP DELETE call with "Content-Type: application/json". How can i do this using libcurl interface.
1 Answer
I think that the proper way to do it in C++ would be something like this:
CURL *hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(hnd, CURLOPT_URL, "http://some/url/");
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\"key\": \"value\"}");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "content-type: application/json");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);
CURLcode ret = curl_easy_perform(hnd);
// do something...
curl_slist_free_all(headers);
curl_easy_cleanup(hnd);
Note: I've edited the answer to include the cleanup code as suggested by John.
3 Comments
John Hascall
For completeness, at the end use
curl_slist_free_all(headers); to free the header list and curl_easy_cleanup(hnd); to free the handle.Gautham
As stated in this page of libcurl docs - curl.haxx.se/libcurl/c/CURLOPT_POSTFIELDS.html, "Using CURLOPT_POSTFIELDS implies setting CURLOPT_POST to 1." Are you sure it goes as a DELETE request rather than as a POST request?
Fernando
Hi Gautham, yes - this will really make a DELETE. It may change on newer versions, but I have tried it recently and it works. Please note that some servers may not accept it, not because of "CURLOPT_POSTFIELDS" but because it is a DELETE that has a BODY - and according to RFC 7231: "(...) sending a payload body on a DELETE request might cause some existing implementations to reject the request"; So, I would recommend that you try it and see if it works in your use case. Good luck!