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