使用C REST SDK(Casablanca)的HTTP_CLIENT POST请求

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

本文关键字:HTTP CLIENT POST 请求 REST SDK Casablanca 使用      更新时间:2023-10-16

我正在尝试使用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();
}

类似的事情将为您做:

        web::json::value json_return;
        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;

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

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

在使用JSON对象之后,与第一个示例相同。如果您从文件中读取JSON,则略容易。