Basic usage of C ++ rest sdk and restsdk

Source: Internet
Author: User

Basic usage of C ++ rest sdk and restsdk

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;using namespace web::http;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 fileStream->close();});try{requestTask.wait();}catch (const std::exception& e){cout << e.what() << endl;}}

In this example, the content of the "Casablanca codeplexfile" 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.

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(methods::GET, builder.to_string()).get();    response.body().read_to_end(fileStream->streambuf()).get();    fileStream->close().get();}

Note that the get () method above 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 url parameters

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 in json or binary format. Let's look at an example of a request body in post json format, the rest sdk provides json objects for json parsing and is convenient to use:

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");

If the request body is in binary format, send the request as follows:

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

Http Response Processing:

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

Initialization is required when wcout is used to output wide characters; otherwise, the content may not be output.

Wcout. imbue (locale ("chs"); // localized

You 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 it to 90 seconds for timeout http_client (URL, config );


Conclusion: The usage of C ++ rest sdk is very simple. uri parsing and splicing, json processing, and request and Response Processing have corresponding objects, it is easy to use. The C ++ rest sdk provided by Microsoft is really a good thing and deserves further research.

Related Article

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.