C++ CURL:以不同方式处理 header 和 body 数据

C++ CURL: treating header and body data differently

我想编写一个 C++ 程序将返回的 header 保存到一个变量并将返回的 body 保存到一个文本文件。我该怎么做?

目前我的做法是重载handleData函数,但是编译returns报错overloaded function with no contextual type information。这是我到目前为止所写的(代码摘录):

static size_t handleData(char *ptr, size_t size, size_t nmemb, string *str){ 
    string temp = string(ptr);
    // catch the cookie 
    if (temp.substr(0,10)=="Set-Cookie"){
       *str = temp;
    }
    return size * nmemb;
}

static size_t handleData(char *ptr, size_t size, size_t nmemb, FILE *stream){ 
    int written = fwrite(ptr, size, nmemb, stream);
    return written;
}

FILE *bodyfile;
string *return_header = new string;

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, handleData); 
curl_easy_setopt(curl, CURLOPT_HEADERDATA, return_header);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, bodyfile);

您应该改用 CURLOPT_HEADERFUNCTION

static size_t handleHeader(char *ptr, size_t size, size_t nmemb, string *str){ 
    // ...
}
static size_t handleData(char *ptr, size_t size, size_t nmemb, FILE *stream){ 
    // ...
}

curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, handleHeader);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, handleData); 
curl_easy_setopt(curl, CURLOPT_HEADERDATA, return_header);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, bodyfile);