Unicode C++
Unicode C++
curl POST with JSON Input and JSON Output
See more CURL Examples
Demonstrates running a simple curl command with JSON input and JSON output.Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkHttpCurlW.h>
#include <CkJsonObjectW.h>
void ChilkatSample(void)
{
bool success = false;
// Run the following curl command
// curl -X POST https://httpbin.org/post \
// -H "Content-Type: application/json" \
// -d '{
// "title": "foo",
// "body": "bar",
// "userId": 1
// }'
// The backslashes at the end of lines are not required. Chilkat ignores them if present.
CkStringBuilderW sbTargetCurl;
sbTargetCurl.AppendLn(L" curl -X POST https://httpbin.org/post \\");
sbTargetCurl.AppendLn(L" -H \"Content-Type: application/json\" \\");
sbTargetCurl.AppendLn(L" -d '{");
sbTargetCurl.AppendLn(L" \"title\": \"foo\",");
sbTargetCurl.AppendLn(L" \"body\": \"bar\",");
sbTargetCurl.AppendLn(L" \"userId\": 1");
sbTargetCurl.AppendLn(L" }'");
CkHttpCurlW httpCurl;
// Run the curl command.
success = httpCurl.DoYourThing(sbTargetCurl.getAsString());
if (success == false) {
wprintf(L"%s\n",httpCurl.lastErrorText());
return;
}
CkJsonObjectW responseJson;
responseJson.put_EmitCompact(false);
httpCurl.GetResponseJson(responseJson);
int statusCode = httpCurl.get_StatusCode();
wprintf(L"response status code: %d\n",statusCode);
wprintf(L"%s\n",responseJson.emit());
// Output:
// response status code: 200
// {
// "args": {},
// "data": "{\r\n \"title\": \"foo\",\r\n \"body\": \"bar\",\r\n \"userId\": 1\r\n }",
// "files": {},
// "form": {},
// "headers": {
// "Content-Length": "96",
// "Content-Type": "application/json",
// "Host": "httpbin.org",
// "X-Amzn-Trace-Id": "Root=1-69e8db8b-459b3bdf7b7a3bc749184968"
// },
// "json": {
// "body": "bar",
// "title": "foo",
// "userId": 1
// },
// "origin": "123.222.222.222",
// "url": "https://httpbin.org/post"
// }
// ----------------------------------------------------------------------------------
// Another example:
// curl -X POST https://postman-echo.com/post \
// -H "Content-Type: application/json" \
// -d '{"foo":"bar"}'
const wchar_t *targetCurl = L"curl -X POST https://postman-echo.com/post -H \"Content-Type: application/json\" -d '{\"foo\":\"bar\"}'";
// Run the curl command.
success = httpCurl.DoYourThing(targetCurl);
if (success == false) {
wprintf(L"%s\n",httpCurl.lastErrorText());
return;
}
httpCurl.GetResponseJson(responseJson);
statusCode = httpCurl.get_StatusCode();
wprintf(L"response status code: %d\n",statusCode);
wprintf(L"%s\n",responseJson.emit());
// Output:
// response status code: 200
// {
// "args": {},
// "data": {
// "foo": "bar"
// },
// "files": {},
// "form": {},
// "headers": {
// "host": "postman-echo.com",
// "content-length": "13",
// "content-type": "application/json",
// "x-forwarded-proto": "https",
// "accept-encoding": "gzip, br"
// },
// "json": {
// "foo": "bar"
// },
// "url": "https://postman-echo.com/post"
// }
}