2016-08-13 52 views
0

RESTfulプログラミングから始め、Casablanca sdk(https://github.com/Microsoft/cpprestsdk)を使用してC++でプログラムを作成しようとしています。私はデータ転送などを行うためにGET、POST、PUT、DELメソッドを使う必要があることを知っています。しかし、これを行う方法の例を見つけることはできません。私は現在、クライアントからサーバーに整数値を送信し、サーバーからブール値の応答を取得する必要があります。私はカサブランカのドキュメンテーションやウェブで良い例を見つけることができません。この簡単な転送を行う方法に関する助けをいただければ幸いです。casablancaを使用して受信を受信するC++ rest sdk

答えて

2

documentationとインターネット上のさまざまな例を調べるのに多くの時間を費やすと、おそらく答えが得られました。

基本的に、特定のURLでクライアントの要求を聞くサーバーとして、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'に保存されます

+1

素晴らしい答え。 VC++では 'then'コールバックチェインの代わりに' co_await'を使うことができます –

関連する問題