Libcurl: perform a REST HTTP PUT

The libcurl library does not provide a clear example on how to issue HTTP PUT operations in a REST context; the examples are mainly about file transfers.

For my proxy application this is not really what I need: I want to perform a REST HTTP PUT, keep it simple, meaning without using the "Expect" and "Transfer-Encoding" that libcurl adds by default.
After some struggling I discovered that this behavior can be changed by using the following code:

 CURL * pCurl;
 struct curl_slist *headers = NULL;
 headers = curl_slist_append(headers, "Content-Type: application/json");
 headers = curl_slist_append(headers, "Content-Length: 12345");
 headers = curl_slist_append(headers, "Expect:");
 headers = curl_slist_append(headers, "Transfer-Encoding:");
 pCurl = curl_easy_init();

 curl_easy_setopt(pCurl, CURLOPT_VERBOSE, 1);
 curl_easy_setopt(pCurl, CURLOPT_PUT, 1);
 curl_easy_setopt(pCurl, CURLOPT_URL, "https://your-server.appspot.com/resource/entity/5");
 curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, headers);
 curl_easy_setopt(pCurl, CURLOPT_READFUNCTION, readData);

 CURLcode res = curl_easy_perform(pCurl);
 if (res != CURLE_OK) {
  printf("HTTP call failed: %d\n", res);
 }

 curl_easy_cleanup(pCurl);
 curl_slist_free_all(headers);

Of course this implies that you know upfront the data being sent(in my case, some JSON) and its size.

Comments

  1. How does one know the size of the JSON. Is a strlen enough? For e.g. if the JSON being sent is "{\"on\":true}" is the Content-Length 11?

    ReplyDelete

Post a Comment

Popular posts from this blog

ZWay: getting the device list.

First steps with the ZWay library