【问题标题】:Send Receive using casablanca c++ rest sdk使用 casablanca c++ rest sdk 发送接收
【发布时间】:2016-08-13 13:50:29
【问题描述】:

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

【问题讨论】:

    标签: c++ rest casablanca


    【解决方案1】:

    花更多时间探索documentation 和互联网上的各种示例可能会为您找到答案。

    基本上,您必须设置一个 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”中

    【讨论】:

    • 很好的答案。值得注意的是,使用 VC++,您可以使用 co_await 而不是 then 回调链接