我写过这个基础课:
class SteamHTTP
{
public:
SteamHTTP();
virtual ~SteamHTTP();
void DownloadAllGames(const wxString& username, wxGauge* progress);
private:
CURL* m_curl;
std::stringstream m_currentRequestString;
private:
static size_t write_func(char *ptr, size_t size, size_t nmemb, void *userdata);
static int progress_func(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);
};
SteamHTTP::SteamHTTP()
{
m_curl = curl_easy_init();
}
SteamHTTP::~SteamHTTP()
{
curl_easy_cleanup(m_curl);
}
size_t SteamHTTP::write_func(char *data, size_t size, size_t nmemb, void *userdata)
{
SteamHTTP* ptr = reinterpret_cast<SteamHTTP*>(userdata);
ptr->m_currentRequestString << data;
return size*nmemb;
}
int SteamHTTP::progress_func(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
wxGauge* ptr = reinterpret_cast<wxGauge*>(clientp);
ptr->SetValue(dlnow * 100.0f / dlnow );
return 0;
}
void SteamHTTP::DownloadAllGames(const wxString& username, wxGauge* gauge)
{
std::string url;
CURLcode result;
// Build URL
url = std::string("http://steamcommunity.com/id/") + username.mbc_str() + std::string("/games?tab=all&xml=1");
// Set URL
curl_easy_setopt(m_curl, CURLOPT_URL, url.c_str());
// Follow redirection
curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1);
// Data Callback
curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, SteamHTTP::write_func);
curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, this);
// Progress Callback
curl_easy_setopt(m_curl, CURLOPT_PROGRESSFUNCTION, SteamHTTP::progress_func);
curl_easy_setopt(m_curl, CURLOPT_PROGRESSDATA, gauge);
curl_easy_setopt(m_curl, CURLOPT_NOPROGRESS, FALSE);
// Perform
result = curl_easy_perform(m_curl);
if (result != 0){
wxMessageBox(curl_easy_strerror(result), wxMessageBoxCaptionStr, wxICON_ERROR|wxOK);
}
}
我挣扎的是在libcurl实际完成时可靠地告诉我。有回调吗?我需要它来解析下载的数据。
判断libcurl是否完成以及我可以处理数据的最佳方式是什么?
p.s。:此代码正在进行中,尚需编写检查等。
答案 0 :(得分:4)
当curl_easy_perform()返回时,它就完成了。它是如此简单。检查返回代码以确定它是否成功。
答案 1 :(得分:1)
参数很少:
int function(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);
dltotal
是要下载的总字节数,dlnow是到目前为止下载的字节数。下载在dltotal == dlnow
时完成。
dltotal
是libcurl在此传输中预期下载的总字节数。dlnow
是到目前为止下载的字节数