Sending data from client to server response_tak = client.request(req) I want to add timeout functionality if response doesn't come in particular time

414 views Asked by At
 utility::string_t url = U("http://localhost:8080/api/v1/post_info");
 web::uri uri1( url);
 web::http::client::http_client client( uri1);
 web::http::http_request request;
 pplx::task<web::http::http_response> response_task;
 web::http::http_response response;

 request.set_method( web::http::methods::POST);
 request.set_body(jsondata);
 response_task = client.request(request);
 response = response_task.get();

If response doesn't come from client.request(request); or if it is taking too much time then My .exe will just wait continiously ? So what should I do ?

web::http::client::http_client::http_client( const uri &base_uri, const http_client_config &client_config );

There is this function in cpprestsdk library but nothing much given about this http_client_config class's utility::seconds web::http::client::http_client_config::timeout()const function.

1

There are 1 answers

0
Warmy On

You can set the timeout for all requests by creating the http_client_config object and using void web::http::client::http_client_config::set_timeout ( const T & timeout ), docu. Then you need to give the config class into the constructor as the second parameter, using the method you mentioned web::http::client::http_client::http_client( const uri &base_uri, const http_client_config &client_config );

The class pplx::task<web::http::http_response> is async, if you call .Get() directly it will be blocked. You should either check if the response is already there with

bool done = resp.is_done();

or use a callback function

resp.then([=](pplx::task<web::http::http_response> task)
{
    web::http::http_response  response = task.get();
    ...
});

If is_done() returns false, calling get() will risk blocking the thread, which defeats the purpose of using an asynchronous API in the first place (it will keep GUIs from refreshing and servers from scaling). For this situation, we need to take a different approach: attach a handler function to the task, which will be invoked once the task completes. We do this using the then() function

more information