我的应用程序将打印响应正文保留在控制台中。而没有cout之类的函数或我放入代码内的类似函数。真奇怪。
#include <iostream>
#include <curl.h>
#pragma comment(lib, "libcurldll.lib");
int main() {
CURL* curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "url");
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
return 0;
}
答案 0 :(得分:0)
根据the documentation,libcurl的默认行为是使用stdout
将响应写出到fwrite
。
您将需要像这样覆盖CURLOPT_WRITEFUNCTION
:
size_t my_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) {
cout << "Received " << nmemb << " bytes" << endl;
return nmemb;
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_callback);
您可以通过更改CURLOPT_WRITEDATA来控制userdata
的值,默认情况下它等于stdout
。
编辑:使用std::string
作为内存缓冲区的简单示例:
size_t my_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) {
static_cast<std::string*>(userdata)->append((char*) ptr, size * nmemb);
return nmemb;
}
std::string buf;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
curl_easy_perform(curl);
// do something with buf