我有一个问题,每当我尝试通过libcurls http发送我的post_data1时,都会说错了密码,但是当我在post_data2中使用固定表达式时,它会登录我。当我退出时,它们都是完全相同的字符串。
谁能告诉我为什么libcurl将它们放在 header 中时不一样?或者,如果是这样的话,为什么在我发送它们之前它们会有所不同。
string username = "mads"; string password = "123";
stringstream tmp_s;
tmp_s << "username=" << username << "&password=" << password;
static const char * post_data1 = tmp_s.str().c_str();
static const char * post_data2 = "username=mads&password=123";
std::cout << post_data1 << std::endl; // gives username=mads&password=123
std::cout << post_data2 << std::endl; // gives username=mads&password=123
// Fill postfields
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data1);
// Perform the request, res will get the return code
res = curl_easy_perform(curl);
最佳答案
使用tmp_s.str()
时,您会得到一个临时字符串。您无法保存指向它的指针。您必须将其保存到std::string
并在调用中使用该字符串:
std::string post_data = tmp_s.str();
// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());
如果(且仅当)
curl_easy_setopt
复制了字符串(而不仅仅是保存指针),则可以在调用中使用tmp_s
:// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tmp_s.str().c_str());
但是我不知道函数是复制字符串还是只是保存指针,所以第一种选择(使用
std::string
)可能是最安全的选择。关于c++ - 字符串转换为const char *问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15155277/