0

我刚开始使用 RESTful 编程并尝试使用 Casablanca sdk ( https://github.com/Microsoft/cpprestsdk ) 用 c++ 编写程序。我知道我需要使用 GET、POST、PUT 和 DEL 方法来进行数据传输等。但我似乎找不到任何有关如何执行此操作的示例。我目前需要从客户端向服务器发送一个整数值,并从服务器获取一个布尔响应。我在 Casablanca 的文档或网络中找不到任何好的示例。任何有关如何进行这种简单转移的帮助将不胜感激。

4

1 回答 1

3

花更多的时间在 Internet 上浏览文档和各种示例可能会给您答案。

基本上,您必须设置一个 http 侦听器,作为服务器,它将侦听特定 url 的客户端请求。

然后客户端可以在该 url 上发送数据,与它进行通信。

不过,如果你想以 json 格式交换数据,

服务器看起来像这样

void handle_post(http_request request)
{
    json::value temp;
    request.extract_json()       //extracts the request content into a json
        .then([&temp](pplx::task<json::value> task)
        {
            temp = task.get();
        })
        .wait();
     //do whatever you want with 'temp' here
        request.reply(status_codes::OK, temp); //send the reply as a json.
}
int main()
{

   http_listener listener(L"http://localhost/restdemo"); //define a listener on this url.

   listener.support(methods::POST, handle_post); //'handle_post' is the function this listener will go to when it receives a POST request.
   try
   {
      listener
         .open()                     //start listening
         .then([&listener](){TRACE(L"\nstarting to listen\n");})
         .wait();

      while (true);
   }
   catch (exception const & e)
   {
      wcout << e.what() << endl;
   }
}

客户将是,

int main()
{
   json::value client_temp;
   http_client client(L"http://localhost");
                                        //insert data into the json e.g : json::value(54)
   client.request(methods::POST, L"/restdemo", object)
                .then([](http_response response)
                {
                    if (response.status_code() == status_codes::OK)
                    {
                        return response.extract_json();
                    }
                    return pplx::task_from_result(json::value());
                })
                    .then([&client_temp ](pplx::task<json::value> previousTask)
                    {
                        client_temp = previousTask.get();
                    })
                    .wait();
}

您的服务器回复将存储在“client_temp”中

于 2016-08-29T10:50:53.403 回答