7

I need to make a HTTP DELETE call with "Content-Type: application/json". How can i do this using libcurl interface.

1
  • 2
    Solved this issue. use curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); curl_easy_setopt(curl, CURLOPT_READDATA, &pooh); Commented Mar 21, 2014 at 4:33

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.