LibCurl CURLOPT_URL not accepting string? C++

青春壹個敷衍的年華 提交于 2019-11-29 11:19:18

The parameter passed to curl_easy_setopt for CURLOPT_URL needs to be a char * instead of a std::string. You can get a const char * from a std::string by calling its c_str member function:

std::string url = "http://foo.com/foo.asp?name=" + *i;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

For anyone who ends up here in the future, take a look at the curl manual if you haven't already. There's also an online book.

The documentation for curl_easy_setopt says you need to read about a specific option to know what parameter type to use.

All options are set with an option followed by a parameter. That parameter can be a long, a function pointer, an object pointer or a curl_off_t, depending on what the specific option expects. Read this manual carefully as bad input values may cause libcurl to behave badly!

The documentation for CURLOPT_URL says exactly what the parameter type needs to be.

Pass in a pointer to the URL to work with. The parameter should be a char * to a zero terminated string which must be URL-encoded in the following format:

scheme://host:port/path

for some reason, when I run this it only gets the website with the last string in the vector, and it ignores the other ones. In my case, it skips James and goes straight to Andrew. Why does that happen?

You are looping through all of the names configuring the curl object with a different name on each loop iteration, THEN you are calling curl_easy_perform() only after the loop has finished, so it will retrieve only the last name that was configured. You need to move your call to curl_easy_perform() inside of the loop instead:

for (std::vector<std::string>::const_iterator i = names.begin(); i != names.end(); ++i)
{
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    curl_easy_setopt(curl, CURLOPT_TIMEOUT, long(m_timeout));

    string url = "http://foo.com/foo.asp?name=" + *i;
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt");
    curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1L);

    success = curl_easy_perform(curl);
    if (success != 0) {
        fprintf(stderr, "%s: %s\n", "curl_easy_perform", errbuf);
        // handle the error as needed...
        continue;
    }

    // use the downloaded content as needed...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!