1+
2+ // https://mariusbancila.ro/blog/2017/11/19/revisited-full-fledged-client-server-example-with-c-rest-sdk-2-10/
3+ #include " def.h"
4+ /*
5+ Notice there are slight changes in the way output is formatted, both in the server and the client application. The rest
6+ is mostly unchanged, except for the handling of JSON, that has changed significatly since version 1.1. Again, please see
7+ the original post for an explanation of the code.
8+
9+ The output from running these client and server applications is shown below. On the left is the client output, and on
10+ the right the server output.
11+ */
12+ void display_json (json::value const & jvalue, utility::string_t const & prefix)
13+ {
14+ std::wcout << prefix << jvalue.serialize () << std::endl;
15+ }
16+
17+ pplx::task<http_response> make_task_request (http_client& client, method mtd, json::value const & jvalue)
18+ {
19+ return (mtd == methods::GET || mtd == methods::HEAD) ? client.request (mtd, L" /restdemo" )
20+ : client.request (mtd, L" /restdemo" , jvalue);
21+ }
22+
23+ void make_request (http_client& client, method mtd, json::value const & jvalue)
24+ {
25+ make_task_request (client, mtd, jvalue)
26+ .then ([](http_response response) {
27+ if (response.status_code () == status_codes::OK)
28+ {
29+ return response.extract_json ();
30+ }
31+ return pplx::task_from_result (json::value ());
32+ })
33+ .then ([](pplx::task<json::value> previousTask) {
34+ try
35+ {
36+ display_json (previousTask.get (), L" R: " );
37+ }
38+ catch (http_exception const & e)
39+ {
40+ std::wcout << e.what () << std::endl;
41+ }
42+ })
43+ .wait ();
44+ }
45+
46+ int full_client_main ()
47+ {
48+ http_client client (U (" http://localhost:8888" ));
49+
50+ auto putvalue = json::value::object ();
51+ putvalue[L" one" ] = json::value::string (L" 100" );
52+ putvalue[L" two" ] = json::value::string (L" 200" );
53+
54+ std::wcout << L" \n PUT (add values)\n " ;
55+ display_json (putvalue, L" S: " );
56+ make_request (client, methods::PUT, putvalue);
57+
58+ auto getvalue = json::value::array ();
59+ getvalue[0 ] = json::value::string (L" one" );
60+ getvalue[1 ] = json::value::string (L" two" );
61+ getvalue[2 ] = json::value::string (L" three" );
62+
63+ std::wcout << L" \n POST (get some values)\n " ;
64+ display_json (getvalue, L" S: " );
65+ make_request (client, methods::POST, getvalue);
66+
67+ auto delvalue = json::value::array ();
68+ delvalue[0 ] = json::value::string (L" one" );
69+
70+ std::wcout << L" \n DELETE (delete values)\n " ;
71+ display_json (delvalue, L" S: " );
72+ make_request (client, methods::DEL, delvalue);
73+
74+ std::wcout << L" \n POST (get some values)\n " ;
75+ display_json (getvalue, L" S: " );
76+ make_request (client, methods::POST, getvalue);
77+
78+ auto nullvalue = json::value::null ();
79+
80+ std::wcout << L" \n GET (get all values)\n " ;
81+ display_json (nullvalue, L" S: " );
82+ make_request (client, methods::GET, nullvalue);
83+
84+ return 0 ;
85+ }
0 commit comments