C++ Curl文件下载-错误检查

C++ Curl file download - error check

我正在使用以下功能从服务器下载文件。

void downloadFile(const char* url, const char* fname) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl){
        fp = fopen(fname, "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
}

这样使用的:

downloadFile("http://servera.com/filea.tar.gz","filea.tar.gz");

如何向其中添加错误检查,以便在 filea.tar.gz 不可用或无法访问 servera.com 时,我可以显示我选择的错误消息。

更新 我添加了:

cout << res; 到代码,但这总是 returns 0

服务器 returns 一条 'file not found' 消息,正在下载。无论如何围绕这个?如果找不到或无法访问指定的文件,我想得到一个错误。谢谢

更新 下面显示了一条人类可读的错误消息:

void downloadFile(const char* url, const char* fname) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl){
        fp = fopen(fname, "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
        res = curl_easy_perform(curl);
        cout << curl_easy_strerror(res);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
}

现在我可以得到错误代码,我应该可以更好地捕获它。感谢@YSC 和@Daniel Stenberg

您需要查看 res 的值。参见 curl error codes for all possible values. If res is equal to CURLE_REMOTE_FILE_NOT_FOUND, then the file is probably not available. You can also get error messages from curl using CURLOPT_ERRORBUFFER

如果 res 始终为 0(说 CURLE_OK 会更精确),那么在支持许多协议的 curl 级别上一切可能都很好。错误在 HTTP 级别。您无法解决服务器返回的内容,但是您可以获得 HTTP 状态代码:服务器可能正在返回 404 代码以及 "file not found" 消息。请参阅 了解如何使用 libcurl 执行此操作。如果可以直接使用 curl 程序,可以先在终端中使用 curl -I http://servera.com/filea.tar.gz.

查看 HTTP 应答

curl_easy_perform() returns 描述结果的 CURLcodeRTFM:

  • CURLE_HTTP_RETURNED_ERROR
    如果 CURLOPT_FAILONERROR 设置为 TRUE 且 HTTP 服务器 returns 错误代码 >= 400,则返回此值。