2017-02-21 86 views
3

我想使用C++ REST SDK(卡萨布兰卡)库执行POST HTTP请求,但我没有成功...我也找不到任何最近/工作代码段。 任何人都可以帮助我吗?使用C++ REST SDK(卡萨布兰卡)Http_client post请求

用我下面的代码我得到一个运行时网:: 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(); 
} 
+0

即使我取消注释.as_string()。c_str() – stkhou

+0

如果您将最小代码剪切为N粘贴可运行,它将帮助我们帮助您 –

+0

您是否尝试删除client.request()的最后一个参数(L“application/json”)? – roalz

回答

0

类似的东西会为你做:

 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,它会稍微容易一些。