Basic usage of the C + + REST SDK

Source: Internet
Author: User

Microsoft has developed an open source cross-platform HTTP library--c++ REST SDK (http://casablanca.codeplex.com/), also known as Casablanca Casablanca, a film called this name, perhaps the author of this library is very fond of this movie. As you can see from the rest SDK, it is the rest API, and the children's shoes that are not known to rest can be ordered here and here, as the rest API requests support for application/x-www-form-urlencoded, application/ JSON, Application/octet-stream and other encoding methods, the REST API return values are in JSON form, it is convenient to return objects. Casablanca is developed using C++11, integrates ppl and ASIO, supports asynchronous data streams and Web sockets, and is handy to use. Let's take a look at the official example below:

 #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::o Stream> ();pp lx::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 ("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;}} 

This example saves the contents of the query "Casablanca CodePlex" from Bing.com to a local file result.html, using the PPL serial task. With four asynchronous tasks enabled, the first task is to open a file stream, and then a second task is initiated to initiate a query request, and then the third task waits for the response of the request and enters the result of the response into the file, and the fourth task is to close the file stream. Note that the character-related entry parameters for the rest SDK are wide characters (wchr_t). This way of handling HTTP allows us to process the HTTP process becomes very clear, a little fresh ^_^, however, this is not familiar with the PPL usage of children's shoes may be a bit difficult to accept, it's okay, let me simplify, simplify to synchronize, see more clearly.

voidtestrequest () {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 blocks the wait for an asynchronous thread to complete the operation. This simplification will make it clearer how to use the rest SDK, and here are a few objects that initiate HTTP operations. Http_client represents the client and requires it to initiate an HTTP request. Rest API is generally based on a basic URL to add some URLs, such as the previous example of search, there may be some URL parameters, at this time, we need to uri_builder to do these stitching URLs and parameters of things, it is very simple to use.

uri_builder Builder;builder.append_path (L"search"// add URL Builder.append_query (L"q", L"Casablanca CodePlex"   Add URL parameter

After the URL and parameters are ready to initiate the request, the request can be used Methods::get and methods::P OST, and so on.

Client.request (Methods::get, builder.to_string ()). Get ();

In the example above, there is no request body, and sometimes we need the request body for the HTTP request, usually JSON or binary format, to see the example of the request body in the Post JSON format, rest The SDK provides JSON objects to parse JSON, which is also handy:

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::P OST, Builder.to_string (), Obj.serialize (), L"Application/json");

If the request body is in binary format, this will be the case:

wchar_t buf[] == Client.request (methods::P OST, Builder.to_string (), buf/*L "" * *, L"application/octet-stream"). Get ();

After the request is initiated, it waits for the HTTP response, and the rest API returns the results in JSON format, so we need to parse the JSON object, and the rest SDK provides the Http_response object to handle the response. Suppose the result of the HTTP response is this:

{    "result":"service failed"    " Error_code "  - }

Handling of HTTP responses:

if(Response.status_code () = =Status_codes::ok) {    Try{result=true; Constjson::value& JV = Response.extract_json ().Get(); ConstWeb::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(Conststd::exception&e) {cout<< e.what () <<Endl; }}

The output of wide characters with wcout requires an initialization, otherwise it may not output content.

Wcout.imbue (the locale ("CHS")); // localization

We can also set the relevant HTTP properties, http_client the default time-out is 30 seconds, we can also set the time-out:

http_client_config config;config.set_timeout (utility::seconds// set to 90-second timeout Http_client Client (URL, config);


Summary: You can see the use of the C + + REST SDK is very simple, URI parsing and splicing, JSON processing, request and response processing have corresponding objects, we use it is very worry. The C + + REST SDK provided by Microsoft is really a good thing, and deserves our deep research.

Basic usage of the C + + REST SDK

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.