Reputation: 467
I successfully send to a REST API a static message following this answer, however when I try to build my dynamic JSON message I have a problem of an extra character that is automatically adding the parsing function in c++, so at the server side, I got an error.
This is the minimal working code of the C++ client that sends the dynamic message:
#include <curl/curl.h>
#include <iostream> //cout
#include <sstream> // std::ostringstream
using namespace std;
int main (int argc, char *argv[]) {
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl == NULL) {
return 128;
}
int x,y,z=0;
for (int var = 0; var < 10; ++var) {
std::ostringstream ssright;
ssright<<"{ \"camID\" : \"";
ssright<<22;
ssright<<"\" , \"x\" : \"";
ssright<<x;
ssright<<"\" , \"y\" : \"";
ssright<<y;
ssright<<"\" , \"z\" : \"";
ssright<<z;
ssright<<"\" }";
const char* jsonObj = ssright.str().c_str();
x+=100; y+=15; z+=500;
std::cout<<ssright.str().c_str()<<std::endl;
std::cout<<jsonObj<<std::endl;
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.4.7:3000/createEmp");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,jsonObj);
//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ssright.str().c_str());
//curl_easy_setopt(curl, CURLOPT_USERAGENT, "camera");
res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
When the server receives this message I got an Unexpected token error, which I think is the end of line token.
SyntaxError: Unexpected token �
If I send the message like this:
const char* jsonObj = "{ \"camID\" : \"22\" , \"x\" : \"0\" , \"y\" : \"0\" , \"z\" : \"0\" }";
The JSON is successfully received at the server.
I also tried to send it like this, but is not working either:
const char* jsonObj = ssright.str().substr(0,ssright.str().size()-1).c_str();
I tried to eliminate the last character of my string, but it keeps adding the end of the line. ssright.str().substr(0,ssright.str().size()-1).c_str()
but is eliminating the '}' and still sending the end of the line.
My question is there is a way to create a dynamic String that does not add the end of the line character? (if this Unexpected token is the end of line character).
Upvotes: 0
Views: 679
Reputation: 37549
You are truncating last character }
from json string and create a dangling pointer to a temporary string buffer.
const char* jsonObj = ssright.str().substr(0,ssright.str().size()-1).c_str();
This should be:
::std::string jsonObjStr(ssright.str());
const char * jsonObj(jsonObjStr.c_str());
Upvotes: 2