简体   繁体   English

在 JSON 格式的发布请求 C++ 中加入变量

[英]Joining a variable inside a JSON formatted post request C++

So I have this put request which submits to a service running on localhost.所以我有这个提交请求,它提交给在本地主机上运行的服务。 Doing it the way below works just fine, note I have replaced the actual acc name with ACC_NAME and password with ACC_PASSWORD.按照下面的方式操作就可以了,注意我已经用 ACC_NAME 替换了实际的 acc 名称,用 ACC_PASSWORD 替换了密码。

curl_easy_setopt(curl_account_login, CURLOPT_POSTFIELDS, "{\r\n  \"username\": \ACC_NAME\,\r\n  \"password\": \"ACC_PASSWORD\,\r\n  \"persistLogin\": false\r\n}\r\n");

However when I wanted to pass in a variable containing the acc_name and acc_password, it does not work, I get an error response from server.但是,当我想传入一个包含 acc_name 和 acc_password 的变量时,它不起作用,我从服务器收到错误响应。 The below request is using the variable joined inside the JSON string, which gives me the error response.下面的请求使用 JSON 字符串中加入的变量,这给了我错误响应。

curl_easy_setopt(curl_account_login, CURLOPT_POSTFIELDS, "{\r\n  \"username\": \""+acc_name+"\,\r\n  \"password\": \""+acc_password+"\,\r\n  \"persistLogin\": false\r\n}\r\n");

I can't figure out what I am doing wrong when I am joining the string variable into the request.当我将字符串变量加入请求时,我无法弄清楚我做错了什么。 It works just fine by plain, if I write the account credentials directly into the request and not in a variable.如果我将帐户凭据直接写入请求而不是变量中,它就可以正常工作。

Regards问候

C-style string literals (like "something" ) are of type const char [] (this is a null-terminated character array), which decays into a const char* (a pointer). C 风格的字符串文字(如"something" )是const char []类型(这是一个以 null 结尾的字符数组),它衰减为const char* (一个指针)。 Thus, + (as in "something" + "another" ) is just adding two addresses, resulting in an invalid pointer value.因此, + (如"something" + "another" )只是添加两个地址,导致指针值无效。 You cannot concatenate C-style strings by simply using + that way.您不能以这种方式简单地使用+来连接 C 样式的字符串。

Assuming you are using C++ (not C), as indicated by your question being tagged , I suggest C++ string objects instead, this will allow easy concatenation.假设您使用的是 C++ (不是 C),正如您的问题被标记,我建议您改为使用 C++ 字符串对象,这将允许轻松连接。

Also, there's a note in curl documentation about CURLOPT_POSTFIELDS , mentioning that the data pointed to is not copied, thus requiring you to make sure the pointer remains valid until the associated transfer finishes.此外,curl 文档中有一条关于CURLOPT_POSTFIELDS的注释,提到指向的数据没有被复制,因此要求您确保指针在相关传输完成之前保持有效。 Because of that, I would prefer using CURLOPT_COPYPOSTFIELDS instead.因此,我更喜欢使用CURLOPT_COPYPOSTFIELDS代替。

To sum up, do something like this:总结一下,做这样的事情:

#include <string>

// ...

std::string postfields
{
    std::string{ "{" } 
    + R"("username":")" + ACC_NAME
    + R"(","password":")" + ACC_PASSWORD
    + R"(","persistLogin":false})"
};

curl_easy_setopt(curl_account_login, CURLOPT_COPYPOSTFIELDS, postfields.data());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM