0
我使用卷曲库与C++来检索这个网址一个非常大的JSON字符串:(它是大约170 000个字符)https://www.bitstamp.net/api/order_book/?group=1卷曲处理大型JSON响应
我的问题是该cURL不会将整个字符串传递给我的回调函数。我用标准的回调函数测试了它,并将整个字符串打印到stdout,所以我可以放心地说,这不是接收数据的问题。但是,只要我的回调函数被调用,传递的数据的大小就是7793或15776个字符。 (我不能认为这可能与这些两个数字的变化correllate任何改变的)
我首先想到的,所以我改变了它从16384至131072,但它并没有帮助的CURL_MAX_WRITE_SIZE值的原因可能:
#ifdef CURL_MAX_WRITE_SIZE
#undef CURL_MAX_WRITE_SIZE
#define CURL_MAX_WRITE_SIZE 131072
#endif
这是我的代码的简要概述:
class EXCHANGE
{
public:
enum { BASE_TYPE }; //to check if template-types are derived from this class
virtual size_t orderbookDataProcessing(void* buffer, unsigned int size, unsigned int nmemb) = 0;
template <typename TTYPE> //only for classes derived from EXCHANGE
static size_t orderbookDataCallback(void* buffer, unsigned int size, unsigned int nmemb, void* userdata)
{
//check if TTYPE is derived from EXCHANGE (BASE_TYPE is declared in EXCHANGE)
enum { IsItDerived = TTYPE::BASE_TYPE };
TTYPE* instance = (TTYPE*)userdata;
if(0 != instance->orderbookDataProcessing(buffer, size, nmemb))
{
return 1;
}
else
{
return (size*nmemb);
}
}
}
class BITSTAMP : public EXCHANGE
{
public:
size_t orderbookDataProcessing(void* buffer, unsigned int size, unsigned int nmemb)
{
string recvd_string; //contains the received string
//copy the received data into a new string
recvd_string.append((const char*)buffer, size*nmemb);
//do stuff with the recvd_string
return 0;
}
}
//main.cpp
///////////////////////////////////
CURL* orderbook_curl_handle = curl_easy_init();
curl_easy_setopt(orderbook_curl_handle, CURLOPT_URL, "https://www.bitstamp.net/api/order_book/?group=1") //URL to receive the get-request
curl_easy_setopt(orderbook_curl_handle, CURLOPT_HTTPGET, 1) //use get method
curl_easy_setopt(orderbook_curl_handle, CURLOPT_NOSIGNAL, 1) //required for multi-threading ?
curl_easy_setopt(orderbook_curl_handle, CURLOPT_WRITEDATA, &bitstamp_USD) //instance passed to the callback-function
curl_easy_setopt(orderbook_curl_handle, CURLOPT_WRITEFUNCTION, (size_t(*)(void*, unsigned int, unsigned int, void*))&EXCHANGE::orderbookDataCallback<BITSTAMP>) //callback function to recv the data
curl_easy_setopt(orderbook_curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE) //do not verify ca-certificate
curl_easy_perform(orderbook_curl_handle);
有了类似[json-c](https://github.com/json-c/json-c)的库,你甚至可以进行渐进式JSON解析:这里是一个[libcurl的具体例子](https:// github.com/deltheil/json-url)。 – deltheil