使用 C++ REST SDK (Casablanca) 的 Http_client 发布请求

stk*_*hou 7 c++ rest sdk post casablanca

我正在尝试使用 C++ REST SDK (Casablanca) 库执行 POST HTTP 请求,但我没有成功......我也找不到任何最近/工作片段。有谁能够帮助我?

使用我的以下代码,我获得了一个运行时web::json::json_exception说“不是字符串”:

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();
}
Run Code Online (Sandbox Code Playgroud)

小智 8

像这样的事情会为你做:

        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;
Run Code Online (Sandbox Code Playgroud)

您也可以像这样简单地解析字符串:

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

就在以与第一个示例相同的方式使用 json 对象之后。如果您从文件中读取 json,则稍微容易一些。