gpt4 book ai didi

c++ - 使用 C++ REST SDK (Casablanca) 的 Http_client post 请求

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:01 25 4
gpt4 key购买 nike

我正在尝试使用 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,会稍微容易一些。

关于c++ - 使用 C++ REST SDK (Casablanca) 的 Http_client post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42370221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com