sha*_*agz 10 c++ libcurl httprequest
我正在尝试将返回的数据从HTTP请求保存到变量中.
下面的代码将自动打印请求的响应,但我需要它来保存对char或字符串的响应.
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;
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*tes 17
我认为你必须写一个函数作为写回调通过CURLOPT_WRITEFUNCTION(见这个).或者,您可以创建一个临时文件并通过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;
}
Run Code Online (Sandbox Code Playgroud)
免责声明:我没有测试过这个,我在C++上有点生疏,但你可以尝试一下.