I am using cpp-httplib and I am trying to upload a file to a post test server like https://ptsv2.com . I do not really understand the given documentation on file uploads, I somewhat understand that you have to make use of Multipart/form-data in order to upload a file.
The given code in the documentation is this
httplib::MultipartFormDataItems items = {
{ "text1", "text default", "", "" },
{ "text2", "aωb", "", "" },
{ "file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain" },
{ "file2", "{\n \"world\", true\n}\n", "world.json", "application/json" },
{ "file3", "", "", "application/octet-stream" },
};
auto res = cli.Post("/multipart", items);
in file1 you can see that it is creating a file on the server and naming it hello.txt.
How do I write it so that I can upload a file that is located on my device onto a server?
Any advice would be helpful. Thank you.
according to #Botje and cpp-httplib documentation
std::ifstream t_lf_img("lfimg.png");
std::stringstream buffer_lf_img;
buffer_lf_img << t_lf_img.rdbuf();
std::ifstream t_pc_file("pc.ply");
std::stringstream buffer_pc_file;
buffer_pc_file << t_pc_file.rdbuf();
httplib::Client cliSendFiles("http://ip::port");
httplib::MultipartFormDataItems items = {
{"files", buffer_lf_img.str(), "lf.png", "application/octet-stream"},
{"files", buffer_pc_file.str(), "truck.ply", "application/octet-stream"},
};
auto resSendFiles = cliSendFiles.Post("/uploadfile", items);
Related
This question already has an answer here:
How to use boost::property_tree to parse JSON with array root
(1 answer)
Closed 2 years ago.
I am using c++ code to read json string to retrieve value based on specific key names. Example of my json response from web API is in array format like below.
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
]
Like the above format is the actual response. I have to retrieve date value using key "date".
My code snippet:
{
std::stringstream jsonString;
boost::property_tree::ptree pt;
jsonString << ws2s(Info).c_str();
boost::property_tree::read_json(jsonString, pt);
std::string date = pt.get<std::string>("date");
}
'Info' in above snippet is wsstring containing json response data.
I can able to retrieve "date" if [] square brackets are removed manually. Since it is array format, if I pass without removing brackets, read_json throws error.
Can somebody help this out?
Yeah. Boost Property Tree is a property tree library, not JSON.
You're in luck though, Boost has a JSON library now https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html
Note: your input isn't valid JSON either, because JSON doesn't strictly allow trailing commas. You can enable them with an option in Boost JSON though:
Live On Compiler Explorer
#include <boost/json.hpp>
#include <iostream>
int main() {
std::string input = R"(
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
])";
boost::json::parse_options options;
options.allow_trailing_commas = true;
auto json = boost::json::parse(input, {}, options);
for (auto& el : json.as_array()) {
std::cout << el.at("date") << "\n";
}
}
Prints
"0000-00-00"
I want to use api with c++ and when I searched I found nlohmann/json library it looks really popular but no one talks about how to get the array that fetch function provides . How can I get the information from the api as variables in my cpp file
Didn’t quite understand your description, I assume you mean you want to get the JSON array? You can try this:
std::string ss= R"(
{
"test-data":
[
{
"name": "tom",
"age": 11
},
{
"name": "jane",
"age": 12
}
]
}
)";
json myjson = json::parse(ss);
auto &students = myjson["test-data"];
for(auto &student : students) {
cout << "name=" << student["name"].get<std::string>() << endl;
}
I've succeeded in my GET request with libcurl, no problems!
However when I try to send a post request, I'm unsure of where I put the json data, I want to be sent over..
My code looks like this, and I wonder if there is a method where I can send over the data as is:
CURL* curlpost;
curl_global_init(CURL_GLOBAL_ALL);
curlpost = curl_easy_init();
if (curlpost) {
curl_easy_setopt(curlpost, CURLOPT_URL, "https://127.0.0.1:50006/lol-lobby/v2/lobby");
// post data:
curl_easy_setopt(curlpost, CURLOPT_POSTFIELDS, "{
"customGameLobby": {
"configuration": {
"gameMode": "CLASSIC", "gameMutator" : "", "gameServerRegion" : "",
"mapId" : 11,
"mutators" : {"id": 1}, "spectatorPolicy" : "AllAllowed", "teamSize" : 5
}
},
"queueId": 830,
"isCustom" : false
}")
That doesn't work and is the raw JSON data I want to send to the server.
How can I send that data to the server is my question?
JSON data to be sent:
{
"customGameLobby": {
"configuration": {
"gameMode": "CLASSIC",
"gameMutator": "",
"gameServerRegion": "",
"mapId": 11,
"mutators": {"id": 1},
"spectatorPolicy": "AllAllowed",
"teamSize": 5
}
},
"queueId": 830,
"isCustom": false
}
Use curl_easy_escape to URL encode the given C string:
char* encoded = curl_easy_escape(curlpost, "{ your post data }", 0);
// use "encoded"
// free the memory
curl_free(encoded);
Using the C# client library for Dialogflow, I am trying to set the output context in a webhook response. However, the output context field is read only. This is my code:
WebhookResponse response = new WebhookResponse
{
FulfillmentText = "This is a test",
OutputContexts = ... //Regardless of what I try and set OutputContexts to be, I get the error "property or indexer 'WebhookResponse.OutputContexts' cannot be assigned to -- it is read only"
};
How do I set the output context?
I know this is an old question but just in case someone has the same problem.
You can not assign a new list to OutputContexts, you have to add them to the list:
For example:
response.OutputContexts.Add(new Context
{
Name = $"{request.Session}/your_context",
LifespanCount = 1
});
I think the response json which you are forming is wrong.
Below is the correct json response which you need to send:
{
"fulfillmentText = "This is a test",
"outputContexts": [
{
"name": "projects/project_id/agent/sessions/session_id/contexts/your_context",
"lifespanCount": 5,
"parameters": {
"foo": "bar",
"foo1": "bar1"
}
}
],
"followupEventInput": {
"name": "even_name"
}
}
I have the following code which should read the contents of a text file and parse it as JSON
try {
string_t importFile = argv[++iArgCounter]; // extract filename
ifstream_t f(importFile); // filestream of working file
stringstream_t s; // string stream for holding JSON read from file
json::value v; // JSON read from input file
iArgCounter++; // increment arg counter
if (f) {
s << f.rdbuf(); // stream results of reading from file stream into string stream
f.close(); // close the filestream
v.parse(s); // parse the resultant string stream.
}
}
catch (web::json::json_exception excep) {
std::cout << "ERROR Parsing JSON: ";
std::cout << excep.what();
break;
}
And the following test JSON file
[
{
"Destinations":
[
{
"Domain": "127.0.0.1",
"Name": "GoogleLogin",
"Port": "8090"
}
],
"Listeners":
[
{
"Domain": "127.0.0.1",
"Name": "LoginRequest",
"Port": "8080",
"Route": "ProcessLoginRequest"
}
],
"Name": "LoginProcess",
"Routes":
[
{
"Name": "ProcessLoginRequest",
"Rules":
[{
"DestinationIfTrue": "GoogleLogin",
"LeftTerm":
{
"RuleTermType": 1,
"Value": "NETWORK"
},
"Operator": 2,
"RightTerm":
{
"RuleTermType": 0,
"Value": "NETWORK"
}
}],
"Transformations": []
}
]
}
]
The trouble is no matter what the JSON code I get the error 'Line 1, Column 2 Syntax error: Malformed token'. From what I can tell the JSON is correctly formatted with all brackets balanced.
Code is running on 64bit Windows 7.
Anyone got an idea why it thinks this (or how I can convert the stringstream_t to a string and see what it actually reads).
change the line
v.parse(s);
to
v = json::value::parse(s)
Could it be that the file is of utf16 encoding?
Or check if your json file has BOM (Byte Oder Mark) at the head by opening it with a hex editor.
Multiple things could go wrong here
Check if the ifstream is able to open the file correctly using the following
if(!f)
cerr << "can't open file";
If this is the case, check if name of the file and location is correct or not
Also replace
v.parse(s);
with
v = json::value::parse(s.str()) /* As parse would take string as input */