c++ - C++ 中的 libcurl : converting URL to some weird symbols

标签 c++ linux c++11 curl libcurl

我注意到 C++ 的 libcurl 更改了提供给一些奇怪符号的 URL。这是代码:

curl_global_init(CURL_GLOBAL_ALL);

curl_handle = curl_easy_init();
cout << "http://subdomain.mydomain.com/folder/check.php?key=" + key << endl;

curl_easy_setopt(curl_handle, CURLOPT_URL, "http://subdomain.mydomain.com/folder/check.php?key=" + addon_key);

curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, &writeCallback);
curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);

res = curl_easy_perform(curl_handle);

这就是我在控制台中得到的:

http://subdomain.mydomain.com/folder/check.php?key=tasdasm34234k23l423m4234mn23n4jk23bjk4b23nasdasdasdasdsdsd
* Rebuilt URL to: � ��g/
* IDN support not present, can't parse Unicode domains
* getaddrinfo(3) failed for �   ��g:80
* Couldn't resolve host '�  ��g'
* Closing connection 0

当我在 Windows 中构建我的项目时,这段代码工作得很好,但是当我在 Linux 中构建它时,就会发生这种情况。如果我只是尝试使用此代码访问“http://subdomain.mydomain.com/folder/check.php”,它会起作用,但只要我添加 key ,libcurl 就会更改整个 URL。

提前致谢。

最佳答案

正如我在评论中所说,CURL 库是一个 C 函数库,而 C 函数对 C++ 中的对象或类一无所知。

当你执行 "http://subdomain.mydomain.com/folder/check.php?key="+ addon_key 结果是一个(临时的)std::string 对象。将其传递给 C 函数将不会很好地工作,令我惊讶的是编译器实际上允许您毫无提示地传递该参数。我认为这应该是一个编译器错误,或者至少应该给你一个严厉的警告。

您可以通过创建另一个变量来存储字符串对象来解决这个问题,并使用 c_str 成员函数来获取 C 风格的字符串(指向常量 char):

std::string url = "http://subdomain.mydomain.com/folder/check.php?key=" + addon_key;
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());

我不知道 cURL 是否复制字符串,或者您是否需要在完成之前保持 url 变量有效。

它显然可以在 Windows 上运行,这完全是运气。将 C++ 对象传递给不期望它的函数是未定义的行为

关于c++ - C++ 中的 libcurl : converting URL to some weird symbols,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38446091/

相关文章:

c++ - 最小化锁争用 c++ std::map

c++ - typeid 的可读形式?

c - X11 - XCreateImage、Visual * vis 参数

c++ - Qt应用程序启动崩溃

c++ - 为什么 std::unique_ptr operator* 会抛出而 operator-> 不会抛出?

c++ - 如何加快将文本文件加载到多 vector

c++ - 用户定义的无序映射哈希函数

c++ - 字符串对的高效安全存储 C++

c++ - 常量存储在哪里以及如何存储?

linux - ec2 实例状态检查失败