gpt4 book ai didi

c++ - 将响应保存到变量中的 libcurl HTTP 请求 - C++

转载 作者:可可西里 更新时间:2023-11-01 15:42:14 26 4
gpt4 key购买 nike

我正在尝试将从 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;
}

最佳答案

我认为您必须编写一个函数,通过 CURLOPT_WRITEFUNCTION 作为写入回调传递(参见 this)。或者,您可以创建一个临时文件并通过 CURLOPT_WRITEDATA(该页面上列出的下一个选项)传递其文件描述符。然后您将从临时文件中将数据读回一个字符串。不是最漂亮的解决方案,但至少您不必弄乱缓冲区和函数指针。

编辑:因为您不想写入文件,所以这样的事情可能会起作用:

#include <string>

size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) {
((string*)stream)->append((char*)ptr, 0, size*count);
return size*count;
}

int main(void) {
// ...
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/");

string response;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

res = curl_easy_perform(curl);
curl_easy_cleanup(curl);

// The "response" variable should now contain the contents of the HTTP response
}
return 0;
}

免责声明:我还没有测试过这个,我对 C++ 有点生疏,但你可以试试看。

关于c++ - 将响应保存到变量中的 libcurl HTTP 请求 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com