向C+发出POST请求+;到REST服务器 我试图从一个C++程序中进行POST请求,它将在数据库中插入/更新条目。p>

向C+发出POST请求+;到REST服务器 我试图从一个C++程序中进行POST请求,它将在数据库中插入/更新条目。p>,c++,rest,http,post,libcurl,C++,Rest,Http,Post,Libcurl,我目前使用的是libcurl,但我必须对POST参数进行strcat(),并将整数转换为字符数组: //first parameter: name=user.name char str[] = "name="; strcat(str, user.name); //converting int to char array: &number=user.number strcat(str, "&number="); uint16_t number_int = user.number;

我目前使用的是libcurl,但我必须对POST参数进行strcat(),并将整数转换为字符数组:

//first parameter: name=user.name
char str[] = "name=";
strcat(str, user.name);

//converting int to char array: &number=user.number
strcat(str, "&number=");
uint16_t number_int = user.number;
stringstream number_str;
number_str << number_int;
string number_temp = number_str.str();
char *number_char = (char*) number_temp.c_str();
strcat(str, number_char);

//the whole thing: "name=user.name&number=user.number"
char *data = str;
char addr[] = "192.168.1.26:5000/api/v0.1/users";
char *address = addr;

auto curl = curl_easy_init();
if (curl) {
  curl_easy_setopt(curl, CURLOPT_URL, address);
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

  CURLcode res = curl_easy_perform(curl);
  curl_easy_cleanup(curl);
  curl = NULL;
}
其中“someName”和“someNumber”是变量


<>编辑:有没有更好的方法来用C++来处理不同参数的POST请求(避免了int转换为char数组和连接)?感谢您指出这一点。为什么您不直接使用
std::string
并在最后通过
myData.cstr()将字符串传递给curl转换它呢?请记住,您还应该通过
curl\u easy\u escape
对参数对进行URL编码。感谢您指出这一点。为什么您不直接使用
std::string
并在最后通过
myData.cstr()将字符串传递给curl转换它呢?请记住,您还应该通过
curl\u easy\u escape
curl -X POST 192.168.1.26:5000/api/v0.1/users --data 'name=someName&number=someNumber'