【问题标题】:"failed writing body & data" libcurl c++“写入正文和数据失败”libcurl c++
【发布时间】:2014-01-10 11:02:52
【问题描述】:

您好,我正在尝试保存 CURL 服务器响应并收到以下错误: 我读到这是由于读取和写入文件的数据大小不同,所以 curl 很糟糕。文件已创建并包含所需的 XML 数据,但仍显示错误。谢谢你的帮助!!

  • 写入正文失败 (0 != 96)

  • 写入数据失败

  • 关闭连接 #0

这是我的 cb 函数:

static size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{  size_t written = fwrite(ptr, size, nmemb, stream); return written; }

和方法:

createJob(std::string s, std::string 目录) {

    static const char *fp = "resultcurl.xml";
    std::stringstream filepath;
filepath<< directory;
    filepath<< fp;

    std::string pagefilename = filepath.str();

FILE *pagefile;
    std::string job_id;

struct curl_slist *headers = NULL;

std::string jobXML = s;
curl = curl_easy_init();

if (curl) {

    headers = curl_slist_append(headers, "Accept: */*");
    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_URL,
            ".../jobs.xml");

    curl_easy_setopt(curl, CURLOPT_USERPWD, "...");

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

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,write_data);

            pagefile = fopen(pagefilename.c_str(), "wb");

       if (pagefile) {


            curl_easy_setopt(curl, CURLOPT_FILE, pagefile);

            //curl_easy_perform(curl);


          }

          res = curl_easy_perform(curl);

            /* cleanup curl stuff */ 
          curl_easy_cleanup(curl);

           //job_id =readXMLvalue(pagefilename);
          fclose(pagefile);
          return 0;

}

【问题讨论】:

  • CURLOPT_WRITEDATA 也出现同样的错误
  • 对不起,我忘了证明所有的方法。它具有文件路径,并且文件包含数据:o 不为空。这让我很困惑。

标签: c++ curl libcurl


【解决方案1】:

交换设置顺序,

   pagefile = fopen(pagefilename.c_str(), "wb");
   if (pagefile) {
        curl_easy_setopt(curl, CURLOPT_FILE, pagefile);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,write_data);
        ...
   }
   ...

【讨论】:

  • tnx 如果我将 writefunction 放在 if 部分中,它就可以工作
【解决方案2】:

如果您只想将数据写入文件,Curl 会为您完成。设置

if(curl_easy_setopt( curl , CURLOPT_WRITEDATA , (void *) fptr  ) != CURLE_OK)
{
    return(YOUR_ERR_CODE) ;
}

fptr 在哪里,

FILE *fptr = fopen( "emalware.127.5a6ceb78050f80e4c833dcc3764bf9dd.gzip", "wb" );
if( fptr == NULL )
{
   return -1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多