CppRestApi communication

Admin私のストア

In Routing, http_listener was registered using cpprestsdk.

Next, let's look at client and server communication.

To send JSON data from the client and obtain the server's response, define a function for the return value of pplx::task<ResponseData>.

pplx::task<ResponseData> is created using pptx::create_task with a lambda expression that returns the ResponseData type.

pplx::task<ResponseData> async(Arg arg) {

return pptx::create_task([capture]

::web::http::client::http_client client(url);

// Send the request. Call the lambda expression registered in the then method with client.request as an argument.

return client.request(::web::http::methods::<GET|PUT|POST|DEL>);

}).then([capture](::web::http::http_response response) {

//For PUT, POST, and DEL requests, this returns the request status and ends the request. ResponseData is void.

return;

//For the GET method, expand the body to cpprestapi json.

return response.extract_json;

}).then([capture](::web::json::value json) {

ResponseData response_data;

response_data = response_json_conver_to_poroject_type(json);

return data;

});

}

In CppRestApi Use the Format::Record constructor in the response_json_conver_to_propoject_type function. By specifying tuple or json in the Format::Record constructor, you can handle data in a unified format in the project without having to worry about data entry. Use ::web::json::value record.json between the server and client, and tuple record.record between the database as the interface.

When exchanging data between the server and client in cpprestsdk, it is converted to ::web::json::value format. Even if the C++ character code of the server and client is different, communication is done through ::web::json::value serialization.

When calling the above async functions on the client, you can choose to communicate synchronously or asynchronously.

Wait for the processing using async(arg).then().await().

Asynchronous communication is performed using async(arg).then().then([this](pptx::task<void> previous_task) {previous_task.wait();}).

On the server side, return ::web::json::value response_json.

void get(::web::http::http_request req) {

::web::json::value response_json;

req.reply(::web::http::status_codes::OK, response_json);

return;

}

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.