如何在 C++ 中使用 libcurl 将字符串传递给 REST API
How to pass string to REST API using libcurl in cpp
我想将字符串发送到 c++ 中的其余 API 调用。所以,我正在使用 libcurl 库。
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"hi\" : \"there\"}");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << res << std::endl;
}
O/P 来自烧瓶 API 是,
ImmutableMultiDict([('{"hi" : "there"}', '')])
以上代码有效:
我正在 python Flask 应用程序中收到发送的结果。
但是,
string body = "{\"hi\" : \"there\"}";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << res << std::endl;
}
来自烧瓶 API 的 O/P 是:
ImmutableMultiDict([('��-ؿ\x7f', '')])
此代码无效。唯一的区别是我将字符串分配给一个变量并将其传递给 curl。
我想知道它为什么有效?
如何将变量传递给 curl?
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ...);
需要一个 char*
作为它的参数,你在第一个例子中给了它,但在第二个例子中没有。请尝试 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
。
在 C++ 中,字符串文字的类型为 char*
(实际上并非如此,但现在足够接近)这是 C 的遗留物。string
类型不同。如果您有 C++ 字符串但需要调用需要旧 C 字符串的函数,请使用 string::c_str()
。
curl_easy_setopt
是一个具有类 C 接口的函数,它使用 "variadic arguments",因为这些参数的类型取决于所设置的选项。
这意味着它不是类型安全的。您的编译器无法检测到您何时使用了错误的类型,就像您在此处所做的那样。 CURLOPT_POSTFIELDS
wants a char*
(指向某些 char
的指针),而不是 std::string
(复杂的 C++ class 类型)。
因此,您不应该传递 std::string
,并且不清楚您认为应该传递的原因,因为文档清楚地指出 char*
是预期的。
但是,您至少应该收到编译器发出的关于通过可变参数模板传递非 PODs 的警告。打开警告,并阅读文档。
我想将字符串发送到 c++ 中的其余 API 调用。所以,我正在使用 libcurl 库。
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"hi\" : \"there\"}");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << res << std::endl;
}
O/P 来自烧瓶 API 是,
ImmutableMultiDict([('{"hi" : "there"}', '')])
以上代码有效:
我正在 python Flask 应用程序中收到发送的结果。
但是,
string body = "{\"hi\" : \"there\"}";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << res << std::endl;
}
来自烧瓶 API 的 O/P 是:
ImmutableMultiDict([('��-ؿ\x7f', '')])
此代码无效。唯一的区别是我将字符串分配给一个变量并将其传递给 curl。
我想知道它为什么有效? 如何将变量传递给 curl?
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ...);
需要一个 char*
作为它的参数,你在第一个例子中给了它,但在第二个例子中没有。请尝试 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
。
在 C++ 中,字符串文字的类型为 char*
(实际上并非如此,但现在足够接近)这是 C 的遗留物。string
类型不同。如果您有 C++ 字符串但需要调用需要旧 C 字符串的函数,请使用 string::c_str()
。
curl_easy_setopt
是一个具有类 C 接口的函数,它使用 "variadic arguments",因为这些参数的类型取决于所设置的选项。
这意味着它不是类型安全的。您的编译器无法检测到您何时使用了错误的类型,就像您在此处所做的那样。 CURLOPT_POSTFIELDS
wants a char*
(指向某些 char
的指针),而不是 std::string
(复杂的 C++ class 类型)。
因此,您不应该传递 std::string
,并且不清楚您认为应该传递的原因,因为文档清楚地指出 char*
是预期的。
但是,您至少应该收到编译器发出的关于通过可变参数模板传递非 PODs 的警告。打开警告,并阅读文档。