libcurl HTTP 请求将响应保存到变量中 - c++
我正在尝试将 HTTP 请求返回的数据保存到变量中。
下面的代码将自动打印请求的响应,但我需要它将响应保存到字符或字符串。
int main(void)
{
char * result;
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您必须编写一个函数来通过
CURLOPT_WRITEFUNCTION
作为写入回调传递(请参阅这个)。或者,您可以创建一个临时文件并通过 CURLOPT_WRITEDATA 传递其文件描述符(该页面上列出的下一个选项)。然后,您会将临时文件中的数据读回字符串中。这不是最漂亮的解决方案,但至少您不必弄乱缓冲区和函数指针。编辑:由于您不想写入文件,因此类似这样的方法可能会起作用:
免责声明:我还没有测试过这个,而且我有点生疏在 C++ 上,但你可以尝试一下。
I think you will have to write a function to pass as a write callback via
CURLOPT_WRITEFUNCTION
(see this). Alternatively you could create a temporary file and pass its file descriptor viaCURLOPT_WRITEDATA
(the next option listed on that page). Then you would read back the data from the temporary file into a string. Not the prettiest of solutions, but at least you don't have to mess with buffers and function pointers.EDIT: Since you don't want to write to a file, something like this might work:
DISCLAIMER: I haven't tested this, and I'm a bit rusty on C++, but you can try it out.
以下是一个示例 http://code. google.com/p/aws4c/source/browse/trunk/aws4c.c#637。
T.Yates 是对的,你必须创建一个接收数据的函数。并使用 CURLOPT_WRITEFUNCTION 让 CURL 了解您的函数。
Here is an example for you http://code.google.com/p/aws4c/source/browse/trunk/aws4c.c#637.
T.Yates is right, you have to make a function that will receive the data. And let CURL know about your function using CURLOPT_WRITEFUNCTION.
为了使代码更容易理解,我将使用类似这样的
write_to_string
函数。To make the code more understandable, I would have the
write_to_string
function something like this.