简体   繁体   English

C ++ curl_easy_perform()将换行符插入响应

[英]C++ curl_easy_perform() inserts newline into response

I'm fetching 43182 chars long JSON from remote REST API using following code snippet: 我正在使用以下代码片段从远程REST API提取43182个字符长的JSON:

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: 我在result_得到的是完整的JSON,但在字符31954之后有换行符:

JSON中的换行符

If I fetch same JSON in browser or command-line curl there is no newline character. 如果我在浏览器或命令行curl中获取相同的JSON,则没有换行符。 How to fix this problem for "arbitrarily" long JSON or other generic response? 如何为“任意”长的JSON或其他通用响应解决此问题?

From CURL document of the write callback: 从写回调的CURL 文档

The data passed to this function will not be zero terminated! 传递给该函数的数据不会被零终止!

The response in WriteCallback is not necessarily null terminated. WriteCallbackresponse不一定为null终止。 So calling append by just casting it to char* will invoke undefined behavior. 因此,仅将其强制转换为char*来调用append会调用未定义的行为。 You have to pass the amount of data too in append . 您还必须在append传递数据量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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