libcurl 从curl_easy_perform()获取数据的问题
这可能是一个愚蠢的问题,但我如何真正获取由curl_easy_perform()
返回的站点数据到我可以使用的变量中。当它执行时,我只是在终端上看到它全部闪过。顺便说一句,我正在使用 C。
有什么想法吗?谢谢。
编辑: 这是我正在使用的代码(我正在访问 Twitter Streaming API,我做得正确吗?)
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
curl_easy_setopt(curl, CURLOPT_USERPWD, "JEggers2:password");
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
This is probably a stupid question, but how do I actually get the site data returned by curl_easy_perform()
into a variable that I can work with. When it executes, I just see it all flash by on the Terminal. I am using C, by the way.
Any ideas? Thanks.
EDIT:
This is the code I'm using (I'm accessing the Twitter Streaming API, am I even doing it correctly?)
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
curl_easy_setopt(curl, CURLOPT_USERPWD, "JEggers2:password");
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要将数据写入字符串,您需要设置一个写入回调函数:
此外,还要设置用于接收数据的字符串变量的地址:
回调函数将如下所示:
因为您不知道数据的总大小d 正在接收,因此您需要重新分配指针才能将其放入字符串中。
To get the data into string, you need to set up a write callback function:
Also, the address of your string variable to receive the data:
Callback function would look like this:
Because you won't know the total size of data you'd be receiving so you would need to make pointer re-allocations to get it into a string.
另一个答案在
callback_func
的第一个和最后一个参数的使用中似乎是错误的(请参阅文档)。您收到的实际数据块位于第一个参数ptr
中,而通过CURLOPT_WRITEDATA
传递的指针是最后一个参数。我做了一个完整的可编译示例:
The other answer appears to be wrong in its usage of first and last parameters of
callback_func
(see the docs). Actual chunk of data you received is in the first parameter,ptr
, while the pointer you pass withCURLOPT_WRITEDATA
is the last parameter.I've made a complete compilable example:
函数 writeDataOnStream 有一个名为 buffer 的空指针,该指针保存所有数据(HTML 代码和标头)
CURLOPT_WRITEFUNCTION
CURLOPT_WRITEDATA
The function writeDataOnStream has a void pointer called buffer this pointer hold all data (HTML CODE AND HEADERS)
CURLOPT_WRITEFUNCTION
CURLOPT_WRITEDATA