libcurl,PUT方法,用POSTFI…

原文地址:libcurl,PUT方法,用POSTFIELDS携带body信息call web service 作者:领导力Plus
#include
#include
#include

typedef struct
{
    char *data;
    int size;
} createdata;

int main(void)
{
  CURL *curl;
  CURLcode res;

  createdata data;
  data.data="{"metadata":{"ACL":{"identifier":"L"},"user":{"color":"Red"}}}";
  data.size=strlen(data.data);

  curl = curl_easy_init();
  if(curl) {
   
    curl_easy_setopt(curl, CURLOPT_URL, "http://XXX.XXX.XX.XXX/Test");
    curl_easy_setopt(curl, CURLOPT_USERPWD, "L:password");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");//根据要求,要用PUT方法,但为什么下面的POSTFIELDS会起作用,暂时还没清楚。记得libcurl的文档里说,POSTFIELDS所调用的是POST方法。。。待续。。。。
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.data);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    struct curl_slist *slist = 0;
        slist = curl_slist_append(slist, "Content-Type: XXXX");
        slist = curl_slist_append(slist, "Accept:XXXX");
        slist = curl_slist_append(slist, "XXXX");
        slist = curl_slist_append(slist, "Expect:");//防止Expect:100-Continue

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);//set head

    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);
  }
  return 0;
}

悲催的是等解决了这个问题后才找到了前人的经验,和我的方法是一样的:
转载自: http://curl.haxx.se/mail/lib-2009-11/0001.html
“A slightly different way to do PUT with a fixed string, is to instead: use
CURLOPT_POSTFIELDS and CURLOPT_CUSTOMREQUEST to change the request to a "PUT"
and then you modify the Content-Type: to whatever you want it to be. ”

至少,我还是解决了这个问题。。。还是个菜鸟啊。。。= =

你可能感兴趣的:(libcurl,PUT方法,用POSTFI…)