错误411长度必需c ++,libcurl PUT请求

时间:2013-12-09 08:47:16

标签: c++ libcurl put http-status-code-411

即使我在标题Content-Length中设置,我也收到411错误。我正在尝试发送PUT请求。 struct curl_slist * headers = NULL;

curl = curl_easy_init();
std::string paramiters =
        "<data_file><archive>false</archive><data_type_id>0a7a184a-dcc6-452a-bcd3-52dbd2a83ea2</data_type_id><data_file_name>backwardstep.stt</data_file_name><description>connectionfile</description><job_id>264cf297-3bc7-42e1-8edc-5e2948ee62b6</job_id></data_file>";

if (curl) {

    headers = curl_slist_append(headers, "Accept: */*");
    headers = curl_slist_append(headers, "Content-Length: 123");
    headers = curl_slist_append(headers, "Content-Type: application/xml");


    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");

    curl_easy_setopt(curl, CURLOPT_URL,
            "..url/data_files/new/link_upload.xml");

    curl_easy_setopt(curl, CURLOPT_USERPWD, "kolundzija@example.ch:PASS");

    curl_easy_setopt(curl, CURLOPT_HEADER, 1L);

    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, paramiters.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
            strlen(paramiters.c_str()));

    curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);

    res = curl_easy_perform(curl);

这是来自SERVER的响应:

Host: cloud...
Transfer-Encoding: chunked
Accept: */*
Content-Length: 123
Content-Type: application/xml
Expect: 100-continue

* The requested URL returned error: 411 Length Required
* Closing connection #0

2 个答案:

答案 0 :(得分:0)

好的,老实说,我找不到你的错误。但是你应该从 curl 网站上获得一个例子(首先谷歌点击“curl put c code”):http://curl.haxx.se/libcurl/c/httpput.html

也许混合简单和高级界面会让人感到困惑。

选项CURLOPT_POSTFIELDSCURLOPT_POSTFIELDSIZE让我感到困惑。这是一个看跌请求,为什么他们甚至在那里?使用PUT时,参数位于URL中。身体是不透明的,至少从HTTP的角度来看。

答案 1 :(得分:0)

你不需要使用文件而不使用自定义请求,INstead设置UPLOAD和PUT选项,如下文所述:

http://curl.haxx.se/libcurl/c/httpput.html

与上面的示例不同,他们使用文件作为您的数据结构,您可以使用任何东西来保存您的数据。使用此选项的回调函数全部使用: CURLOPT_READFUNCTION 不同之处在于你如何设置回调函数,只需要做两件事: 1.-以字节为单位测量有效负载(数据)的大小 2.-将数据复制到curl传递给回调的内存地址(这是你回调函数的第一个参数,这个定义中的FIRST void指针)

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)

这是ptr的论点。

使用memcpy复制数据。

看一下这个链接。我遇到了和你一样的问题并且能够使用这种方法解决它,你需要记住的一件事是你还需要在发送curl请求之前设置文件大小。

How do I send long PUT data in libcurl without using file pointers?

使用CURLOPT_INFILESIZE或CURLOPT_INFILESIZE_LARGE。