【问题标题】:C++ curl could not resolve host if URL is provided as argument如果 URL 作为参数提供,C++ curl 无法解析主机
【发布时间】:2016-09-10 11:10:21
【问题描述】:

我正在构建一个需要获取 API 请求的小型应用程序。

如果我直接在函数中提供完整的 URL,我使用 libcurl 效果很好,但如果我在函数内部使用 URL 作为参数,它会立即失败并出现错误 CURLE_COULDNT_RESOLVE_HOST(6)。

所以我知道这不是 DNS 问题,因为如果我直接提供 URL,我可以解决它。

这是我目前的功能。

std::string winget(std::string url)
{

    CURL *curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
        return readBuffer;
}

//and I call it like this :

winget("example.org");

基本上,如果我直接将函数中的 url 参数替换为“example.org”,它就可以工作。所以我真的不知道该怎么处理它。

提前非常感谢。 :)

【问题讨论】:

    标签: c++ curl libcurl


    【解决方案1】:

    在这里找到解决方案:URL Variable passing into Curl

    基本上,您需要将 URL 提供为以空字符结尾的字符串。因此,如果参数是字符串,请使用.c_str() 或从该字符串中获取char*

    【讨论】:

    • curl 的其他参数也可能出现同样的问题。请记住,libcurl 是 C 库,而不是 C++ 库。这意味着 libcurl 不能将 std::string 用于字符串。相反,char* 用于任何类似字符串的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2010-11-23
    • 2011-05-20
    • 2021-12-18
    相关资源
    最近更新 更多