Basic usage of C ++ REST SDK

Source: Internet
Author: User

Basic usage of C ++ REST SDK
Microsoft developed an open-source cross-platform http library-C ++ rest sdk (http://casablanca.codeplex.com/), also known as Casablanca, there is a movie called this name, maybe the authors of this library like this movie. From the name of the rest sdk, we can see that it processes rest APIs. For those who do not know REST, click here and here, rest api requests support application/x-www-form-urlencoded, application/json, application/octet-stream, and Other encoding methods. The return values of REST APIs are in json format, it is convenient to return objects. Casablanca is developed using c ++ 11 and integrates PPL and asio. It supports asynchronous data streams and web sockets, making it easy to use. Let's take a look at an official example: # include <cpprest \ http_client.h> # include <cpprest \ filestream. h> using namespace utility; using namespace web: http: client; using namespace concurrency; void TestRequest () {auto fileStream = std: make_shared <concurrency: streams: ostream> (); pplx: task <void> requestTask = concurrency: streams: fstream :: open_ostream (U ("result.html ")). then ([=] (Concurrency: streams: ostream outFile) {* fileStream = outFile; http_client client (U ("http://www.bing.com/"); uri_builder builder (U ("/search ")); builder. append_query (U ("q"), U ("Casablanca CodePlex"); return client. request (methods: GET, builder. to_string ());}). then ([=] (http_response response) {return response. body (). read_to_end (fileStream-> streambuf ());}). then ([=] (size_t len) {return fileStre Am-> close () ;}); try {requestTask. wait ();} catch (const std: exception & e) {cout <e. in the example of what () <endl ;}}, the content of the Casablanca codeplex”file is saved to result.html in bing.com, And the ppl serial task is used. Four asynchronous tasks are enabled. The first task is to open a file stream, and then the second task is initiated to initiate a query request. Then, the third task waits for the response of the request, and input the response result to the file. The fourth task is to close the file stream. Note that the input parameter related to the characters in the rest sdk is a wide character (wchr_t ). This method of processing http makes the process of processing http clear, a little fresh ^ _ ^. However, it may be a bit unacceptable for children who are not familiar with ppl usage. It doesn't matter, let me simplify it and simplify it into a synchronous method, so we can see it more clearly. Copy the code void TestRequest () {auto fileStream = std: make_shared <concurrency: streams: ostream> (); concurrency: streams: ostream outFile = concurrency: streams:: fstream: open_ostream (U ("result11.html ")). get (); * fileStream = outFile; http_client client (L "http://www.bing.com/"); uri_builder builder (L "/search"); builder. append_query (L "q", L "Casablanca CodePlex"); http_response response = client. request (met Hods: GET, builder. to_string ()). get (); response. body (). read_to_end (fileStream-> streambuf ()). get (); fileStream-> close (). get ();} copy the code. Note that the above get () method will block waiting for the asynchronous thread to complete the operation. After this is simplified, you can see more clearly how to use the rest sdk. The following describes several objects that initiate http operations. Http_client represents the client and needs it to initiate an http request. Rest APIs generally add some URLs based on a basic URL, such as search in the previous example. There may also be some URL parameters. In this case, we need uri_builder to splice these URLs and parameters, it is easy to use. Uri_builder builder; builder. append_path (L "search"); // Add URLbuilder. append_query (L "q", L "Casablanca CodePlex"); // Add the url parameter. After the url and parameters are ready, you can initiate a request. The request method can be methods :: get and methods: POST. Client. request (methods: GET, builder. to_string ()). get (); In the above example, there is no request body. Sometimes we still need the request body to initiate an http request, which is generally in json or binary format, let's take a look at the example of a request body in post json format. The rest sdk provides a json object to parse json, which is also very convenient to use: copy the code uri_builder builder; builder. append_path (L "/test"); json: value obj; obj [L "Count"] = json: value: number (6 ); obj [L "Version"] = json: value: string (L "1.0"); client. request (methods: POST, builder. to_string (), obj. Serialize (), L "application/json"); copy the Code. If the request body is in binary format, send the request in this way: wchar_t buf [48] = {}; http_response response = client. request (methods: POST, builder. to_string (), buf/* L "*/, L" application/octet-stream "). get (); after the request is initiated, it will wait for the http response. The rest api returns the results in json format, so we need to parse the json object. The rest sdk provides the http_response object to process the response. Assume that the http response result is as follows: {"result": "service failed" "error_code": 400} processing of the http response: copying the Code if (response. status_code () = status_codes: OK) {try {result = true; const json: value & jv = response. extract_json (). get (); const web: json: object & jobj = jv. as_object (); auto result = jobj. at (L "result "). as_string (); auto access_code = result. as_object (). at (L "error_code "). as_string (); wcout <result <"" <access_code <Endl;} catch (const std: exception & e) {cout <e. what () <endl ;}} to copy the code and use wcout to output wide characters, An Initialization is required; otherwise, the content may not be output. Wcout. imbue (locale ("chs"); // for localization, we can also set relevant http attributes. The default timeout value of http_client is 30 seconds. You can also set the timeout value by yourself: http_client_config config; config. set_timeout (utility: seconds (90); // set to 90 seconds timeout http_client client (URL, config); summary: the usage of C ++ rest sdk is very simple. uri parsing and splicing, json processing, and request and Response Processing all have corresponding objects, it is easy to use. The C ++ rest sdk provided by Microsoft is really a good thing and deserves further research.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.