如何超时libcurl C++调用和/或知道调用何时发生超时

Ben*_*ney 7 c++ timeout libcurl

我正在尝试使用我的C++程序下载远程html页面,但是有些URL会发生超时,但我不知道如何处理这个,所以程序将无限期挂起.

virtual void downloadpage(string pageaddress) {
    CURL *curl;
        CURLcode informationdownloaded;
        curl = curl_easy_init();
        if (curl) { 
            curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
            curl_easy_setopt(curl, CURLOPT_URL, pageaddress.c_str());
            curl_easy_setopt(curl, CURLOPT_HEADER, 0);
            curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writepageinformation);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &pageinformation);
            informationdownloaded = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我通过"writepageinformation"函数将页面的html源代码下载到名为"pageinformation"的字符串变量的功能.

raj*_*shk 6

informationdownloaded = curl_easy_perform(curl);
Run Code Online (Sandbox Code Playgroud)

您还可以指定下载超时

curl_easy_setopt(hCurl, CURLOPT_TIMEOUT, iTimeoutSeconds); // timeout for the URL to download
Run Code Online (Sandbox Code Playgroud)

在下载整个文件之前,这是一个阻塞调用。如果您有兴趣中断阻塞的调用(用于终止信号),请安装进度回调,如下所示

curl_easy_setopt(hCurl, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(hCurl, CURLOPT_PROGRESSFUNCTION, progress_callback);
curl_easy_setopt(hCurl, CURLOPT_PROGRESSDATA, this);

static int progress_callback(void *clientp,
                           double dltotal,
                           double dlnow,
                           double ultotal,
                           double ulnow)
{
    CLASS &obj = *(CLASS*)clientp;


    if (obj.exit)
      return 1; // if u want the signal curl to unblock and return from curl_easy_perform

    return 0; // if u want the callback to continue
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*erg 3

使用 CURLOPT_TIMEOUT 选项?

使用 CURLOPT_PROGRESSFUNCTION 回调并在您认为足够时停止操作?

使用 CURLOPT_LOWSPEED 选项或类似选项使其取决于传输速率。