gpt4 book ai didi

c++ - LibCurl CURLOPT_URL 不接受字符串? C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:17 27 4
gpt4 key购买 nike

所以基本上我想做的是使用 libcurl 来获取略有不同的 url,例如:

http://foo.com/foo.asp?name=*NAMEHERE*

我想做的是遍历一个名称 vector 并获取每个名称,例如:

http://foo.com/foo.asp?name=James

然后

http://foo.com/foo.asp?name=Andrew

等等。

但是,当我尝试这样做时:

int foo (){
CURL *curl;
CURLcode success;
char errbuf[CURL_ERROR_SIZE];
int m_timeout = 15;

if ((curl = curl_easy_init()) == NULL) {
perror("curl_easy_init");
return 1;
}

std::vector<std::string> names;

names.push_back("James");
names.push_back("Andrew");

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));
curl_easy_setopt(curl, CURLOPT_URL, "http://foo.com/foo.asp?name=" + *i);
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);
}

if ((success = curl_easy_perform(curl)) != 0) {
fprintf(stderr, "%s: %s\n", "curl_easy_perform", errbuf);
return 1;
}

curl_easy_cleanup(curl);

return 0;
}

它给我一个错误:

Cannot pass object of non-trivial type 'std::__1::basic_string<char>' through variadic function; call will abort at runtime

在这一行:

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

因为 + *i

我想做的事可行吗?有解决办法吗?

编辑:感谢您的回答,但出于某种原因,当我运行它时,它只会获取 vector 中最后一个字符串的网站,而忽略其他字符串。在我的例子中,它跳过了 James 并直接转到了 Andrew。为什么会这样?

最佳答案

CURLOPT_URL 传递给 curl_easy_setopt 的参数需要是 char * 而不是 std::string。您可以通过调用 c_str 成员函数从 std::string 获取 const char *:

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

对于将来来到这里的任何人,请查看 curl manual如果你还没有。还有一个 online book .

curl_easy_setopt 的文档表示您需要阅读特定选项以了解要使用的参数类型。

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!

CURLOPT_URL 的文档准确说明参数类型需要是什么。

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

关于c++ - LibCurl CURLOPT_URL 不接受字符串? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23721344/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com