Reputation: 23
I am trying to replicate the following curl command in c++ code using the curl library but with no luck. The curl command is (the url is an actual url I am just hiding it):
curl -iX PATCH '*URL*/attrs/topicData' \
-H 'Content-Type: application/json' \
-H 'Link: <http://context-provider:3000/data-models/ngsi-context.jsonld>; rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json"' \
--data-raw '{
"value": "Hi, new data test",
"type": "Property"
}'
This works perfectly fine and updates the value as required. My issues is that I can't replicate it in c++ code. I am using the nlohmann json library just in case that helps.
My c++ code is:
json ent={
{"type","Property"},
{"value","updated successfully"}
};
curl_global_init(CURL_GLOBAL_DEFAULT);
std::string json_entity = ent.dump();
curl = curl_easy_init();
if (curl) {
// Add headers
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, R"(Link: <http://context-provider:3000/data-models/ngsi-context.jsonld>; rel="http://w3.org/ns/json-ld#context"; type="application/ld+json")");
// Set custom headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// Set URL
curl_easy_setopt(curl, CURLOPT_URL, "*URL*/attrs/topicData");
// Set request type
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH");
// Set values
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,json_entity);
// Perform the request which prints to stdout
result = curl_easy_perform(curl);
// Error check
if (result != CURLE_OK) {
std::cerr << "Error during curl request: "
<< curl_easy_strerror(result) << std::endl;
}
//Free header list
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
else {
std::cerr << "Error initializing curl." << std::endl;
}
The error that I am getting is: "type":"http://uri.etsi.org/ngsi-ld/errors/InvalidRequest", "title":"Invalid request.", "details":"Invalid request."
I think my issue is at set values command but I am not sure what the problem is.
Can anyone please advice me on what I am doing wrong?
Upvotes: 2
Views: 3904
Reputation: 117318
CURLOPT_POSTFIELDS
expects a char*
but you are supplying a std::string
.
This should be working better:
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_entity.data());
Upvotes: 4