c libcurl POST不能始终如一地工作

时间:2010-12-14 18:42:35

标签: c xml post curl libcurl

我正在尝试使用libcurl将cml数据从c程序发布到网站。当我在linux中使用命令行程序时,像这样卷曲它可以正常工作:

卷曲-X POST -H'内容类型:text / xml'-d'我的xml数据'http://test.com/test.php

(为了安全起见,我更改了实际数据)

但是一旦我尝试使用libcurl编写c代码,它几乎每次都会失败,但每隔一段时间就会成功。这是我的c代码:

CURL *curl;
CURLcode res;

curl = curl_easy_init();

if(curl)
{
    curl_easy_init(curl, CURLOPT_URL, "http://test.com/test.php");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmlString.c_str());
    curl_easy_perform(curl);
}

curl_easy_cleanup(curl);

我将这段代码放在一个大约每10秒运行一次的循环中,它只会在每4或5次调用时成功。我从服务器上找到了“找不到XML头”的错误。

我尝试使用以下命令指定HTTP标头:

struct curl_slist *chunk = NULL
chunk = curl_slist_append(chunk, "Content-type: text/xml");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

但我没有运气。有什么想法吗?

1 个答案:

答案 0 :(得分:8)

试试这个:

CURL *curl = curl_easy_init(); 
if(curl) 
{ 
    curl_easy_setopt(curl, CURLOPT_URL, "http://test.com/test.php"); 
    curl_easy_setopt(curl, CURLOPT_POST, 1); 
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmlString.c_str()); 
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, xmlString.length()); 
    struct curl_slist *slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using...
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); 
    curl_easy_perform(curl); 
    curl_slist_free_all(slist);
    curl_easy_cleanup(curl); 
} 
相关问题