简体   繁体   中英

C++ curl_easy_perform() inserts newline into response

I'm fetching 43182 chars long JSON from remote REST API using following code snippet:

string result_;

curl_easy_setopt(curlGET_, CURLOPT_TIMEOUT, CURL_TIMEOUT);
curl_easy_setopt(curlGET_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curlGET_, CURLOPT_VERBOSE, CURL_DEBUG_VERBOSE);
curl_easy_setopt(curlGET_, CURLOPT_WRITEDATA, &result_);
curl_easy_setopt(curlGET_, CURLOPT_WRITEFUNCTION, WriteCallback);

static size_t WriteCallback(void *response,
                            size_t size,
                            size_t nmemb,
                            void *userp) noexcept
        {
            (static_cast<string*>(userp))->append(static_cast<char*>(response));
            return size * nmemb;
        };

curlStatusCode_ = curl_easy_perform(curlGET_);

What I get in result_ is complete JSON but with newline character after character 31954:

JSON中的换行符

If I fetch same JSON in browser or command-line curl there is no newline character. How to fix this problem for "arbitrarily" long JSON or other generic response?

From CURL document of the write callback:

The data passed to this function will not be zero terminated!

The response in WriteCallback is not necessarily null terminated. So calling append by just casting it to char* will invoke undefined behavior. You have to pass the amount of data too in append .

(static_cast<string*>(userp))->append(static_cast<char*>(response), size * nmemb)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM