Casablanca – JSON POST code snippet

Continuing on with Casablance, here’s a code snippet that shows how to POST JSON data to a web server.

json::value postData;
postData[L"name"] = json::value::string(L"Joe Smith");
postData[L"sport"] = json::value::string(L"Baseball");

http_client client(L"http://localhost:5540/api/values");

client.request(methods::POST, L"", postData.to_string().c_str(), 
  L"application/json").then([](http_response response)
  std::wcout <<  response.status_code() << std::endl;

  if(response.status_code() == status_codes::OK)
    auto body = response.extract_string();		

    std::wcout << body.get().c_str();

C++ does not have reflection, so unlike with .NET, you need to manually create the JSON from an object structure (which may seem like too much work if you’ve used JSON libraries in C# where the JSON is easily auto-generated using reflection). But it should not be too difficult to come up with some helper classes/methods that’ll make this easier for you.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s