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

rpl*_*orn 3 c xml post curl libcurl

我正在尝试使用libcurl将acml程序中的xml数据发布到网站上.当我在linux中使用命令行程序时,像这样卷曲它工作正常:

curl -X POST -H'Content-type:text/xml'-d'my xml data'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);
Run Code Online (Sandbox Code Playgroud)

我将这个代码放在一个大约每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);
Run Code Online (Sandbox Code Playgroud)

但我没有运气.有任何想法吗?

Rem*_*eau 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); 
} 
Run Code Online (Sandbox Code Playgroud)