【问题标题】:Sending POST using cpprest使用 cpprest 发送 POST
【发布时间】:2017-04-12 23:07:45
【问题描述】:

我有以下代码可以发送 POST,但即使编译正确,我也会收到错误

http_client client(U("http://l0.71.103.63:34568"));
json::value postData;
postData["name"] = json::value::string(U("Mohammad"));

http_response response = client.request(methods::POST,postData.to_string().c_str()).get();

if(response.status_code() == status_codes::OK)
{
  auto body = response.extract_string();
  std::wcout << L"Added new Id: " << body.get().c_str() << std::endl;

  return std::stoi(body.get().c_str());
}

但我在尝试运行程序时遇到以下错误

terminate called after throwing an instance of 'web::uri_exception'
what():  provided uri is invalid: {"name":"Mohammad"}
Aborted (core dumped)

【问题讨论】:

  • client::requestnumber of overloads 让人眼花缭乱,不过猜测一下,需要在json数据之前传递一个路径。创建 http_client 时,您将什么传递给它?也许您需要从中拆分路径,只留下主机名并将路径传递给client::request
  • @PaulRooney 我创建了如下客户端:http_client client(U("l0.71.103.63:34568"));
  • 您要发布到的资源是什么?你可以用 curl 或任何其他语言(例如 Python 请求)来做吗?您可以尝试"/" 的资源,但这似乎很奇怪。

标签: c++ casablanca cpprest-sdk


【解决方案1】:

我认为问题在于您的 IP 地址。看起来你的IP地址是错误的?你有“http://l0”。其中“10”是“l0”(小写 L)。

因此 web:uri​​_exception。

【讨论】:

    【解决方案2】:

    你的请求是错误的(我认为),应该是这样的:

    自动响应 = client.request(methods::POST, U("\"), postData).get();

    请求中的第二个参数是 URL 补码,并且您以字符串形式传递 json,因此您遇到了错误。
    基本上你想要的语法是这个one:

    pplx::task web::http::client::http_client::request ( const 方法 & mtd, const 实用程序::string_t & path_query_fragment, 常量 json::value & body_data, 常量 pplx::cancellation_token & 令牌 = pplx::cancellation_token::none() )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 2014-10-21
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多