我在 stackoverflow 上阅读了几篇关于 c++/curl 的文章并组装了以下内容。主要目标是在一个类的实例中处理整个请求——也许稍后在辅助线程中。
我的问题是:“content_”虽然地址相同,但似乎保持空白
HttpFetch.h:
class HttpFetch
{
private:
CURL *curl;
static size_t handle(char * data, size_t size, size_t nmemb, void * p);
size_t handle_impl(char * data, size_t size, size_t nmemb);
public:
std::string content_;
static std::string url_;
HttpFetch(std::string url);
void start();
std::string data();
};
HttpFetch.cpp:
HttpFetch::HttpFetch(std::string url) {
curl_global_init(CURL_GLOBAL_ALL); //pretty obvious
curl = curl_easy_init();
content_.append("Test");
std::cout << &content_ << "\n";
curl_easy_setopt(curl, CURLOPT_URL, &url);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content_);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &HttpFetch::handle);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //tell curl to output its progress
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
//std::cout << &content_ << "\n";
}
void HttpFetch::start() {
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
size_t HttpFetch::handle(char * data, size_t size, size_t nmemb, void * p)
{
std::string *stuff = reinterpret_cast<std::string*>(p);
stuff->append(data, size * nmemb);
std::cout << stuff << "\n"; // has content from data in it!
return size * nmemb;
}
主.cpp:
#include "HttpFetch.h"
int main(int argc, const char * argv[])
{
HttpFetch call = *new HttpFetch("http://www.example.com");
call.start();
::std::cout << call.content_ << "\n"
}
提前致谢