Http_client post request using C++ REST SDK (Casablanca)

stkhou picture stkhou · Feb 21, 2017 · Viewed 9.7k times · Source

I'm trying to perform a POST HTTP request using C++ REST SDK (Casablanca) library, but I'm not succeeding... Nor I can find any recent/working snippet. Can anybody help me?

With my following code I obtain a runtime web::json::json_exception saying "not a string":

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

web::http::client::http_client client(L"https://jsonplaceholder.typicode.com/posts");

try
{
    client.request(
        methods::POST,
        L"",
        postData/*.as_string().c_str()*/,
        L"application/json");
}
catch (web::json::json_exception &je)
{
    std::cout << je.what();
}
catch (std::exception &e)
{
    std::cout << e.what();
}

Answer

user6418134 picture user6418134 · Mar 14, 2017

Something like that will do for you:

        web::json::value json_v ;
        json_v["title"] = web::json::value::string("foo");
        json_v["body"] = web::json::value::string("bar");
        json_v["userId"] = web::json::value::number(1);
        web::http::client::http_client client("https://jsonplaceholder.typicode.com/posts");
        client.request(web::http::methods::POST, U("/"), json_v)
        .then([](const web::http::http_response& response) {
            return response.extract_json(); 
        })
        .then([&json_return](const pplx::task<web::json::value>& task) {
            try {
                json_return = task.get();
            }
            catch (const web::http::http_exception& e) {                    
                std::cout << "error " << e.what() << std::endl;
            }
        })
        .wait();

        std::cout << json_return.serialize() << std::endl;

You can also simply parse the string like that:

        web::json::value json_par;
        json_par.parse("{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}");

Just after use the json object the same way than in the first example. It is slightly easier if you read the json from a file.