2

I'm just starting with RESTful programming and trying to make a program in c++ using the Casablanca sdk (https://github.com/Microsoft/cpprestsdk). I know that I need to use GET, POST, PUT and DEL methods to do data transfer etc. But I cant seem to find any examples on how to do this. I currently need to send an integer value to the server from the client and get a Boolean response from the server. I cant find any good examples in Casablanca's documentation or the web. Any help regarding how to do this simple transfer would be appreciated.

f_bhatti
  • 21
  • 1
  • 3

1 Answers1

3

Spending more time to explore the documentation and various examples on the internet would probably have got you the answer.

Basically, you have to set up a http listener, as the server, that will listen to client request at a particular url.

Then a client can send data on that url, to communicate with it.

Nevertheless, if you want to exchange data in json format,

Server would look something like this

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;
   }
}

Client would be,

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();
}

Your server reply will be stored into 'client_temp'