C网络库微软开源的cppRestSdk入门环境及使用示例
头条创作挑战赛前言
一般的用客户端实现Webservice有两种方式,一种是基于SOAP协议,另外一种是基于REST,并且REST协议目前是越来越流行。使用C或者java来开发REST客户端目前是比较快捷方便的,毕竟可用的库或资源很多,但使用C开发RESTclient的话就不容易了,毕竟标准C在网络库这一块是没有标注库的,以前开发时候使用过libcurl库(C语言编写)和VC的httpclient,或者使用Qt的QNetworkAccessManager库来进行后台api的调用,实现post、get请求进行数据处理,但或多或少都遇到过一些问题,再到后来别人推荐了微软开源的casablanca,或者叫cppRestSdk库。下面整理一下cppRestSdk库的使用及一些入门示例代码。1、cpprestsdk介绍及编译
cRESTSDK,又叫卡萨布兰卡,是一个微软发布的C基于云的客户机服务器通信库。该库基于现代化的C异步API,即Promise模型或叫链式异步模型设计,c开发人员可以方便地连接并与服务交互。
SDK内容特性HTTP客户机服务器,JSON,URI,异步流,WebSockets客户机,oAuthPPL任务〔2〕一个强大的基于c11特性编写的异步操作模型支持平台Windows桌面,WindowsStore,WindowsPhone,Ubuntu,OSX,iOS和AndroidWindows平台编译支持VS2012、2013年、2015、2017、2019非Windows平台编译支持cmake包管理器支持NuGet,仅在VS编译器支持Windows和Android平台
cpprestsdk编译
cpprestsdk的源代码可以在github下载:https:github。commicrosoftcpprestsdk,但编译的过程比较复杂,因为依赖了boost、openssl等库,需要先编译这些库。常用方法有下面三种:
github下载
(1)使用vcpkg安装,但vcpkg这个工具本身需要先下载依赖库的各种源码,此外下载过程中很容易出现资源下载不下来的问题,相对较为麻烦,优点是自动化,只要解决vcpkg下载中的各种问题,编译什么的都是自动的。
(2)使用Visualstudio自带的NuGetpackage包管理器。在visualstudio新建一个c工程,点击工具NuGet程序包管理器管理解决方案的NuGet程序包,打开NuGet包管理器。然后搜索cpprestsdk即可找到,本人用的VS2017IDE,效果如下:
点击安装按钮进行安装,安装完成后,visualstudio自动将cpprestsdk(编译后的lib、include头文件、dll文件)下载到当前项目工程文件所在的路径中。
当然为了方便实用,也可以将编译后的lib、include头文件、dll文件拷贝到自己指定的文件夹下,作为普通的第三方库进行使用。
2、cpprestsdk官方示例
官方示例提供的是一个Get请求,获取urlhttp:www。bing。comsearch?qcpprestsdkgithub返回的html文件,运行结果是将请求到的html网页数据流保存生成results。html文件。
运行结果
示例代码如下:includestdafx。hincludecppresthttpclient。hincludecpprestfilestream。husingnamespaceutility;Commonutilitieslikestringconversionsusingnamespaceweb;CommonfeatureslikeURIs。usingnamespaceweb::http;CommonHTTPfunctionalityusingnamespaceweb::http::client;HTTPclientfeaturesusingnamespaceconcurrency::streams;Asynchronousstreams官方示例Get请求:获取urlhttp:www。bing。comsearch?qcpprestsdkgithub返回的html文件;运行结果:将请求到的html网页数据流保存生成results。html文件std::wstringwsServersiteLhttp:www。bing。com;std::wstringwsURILsearch;std::wstringwsNameLq;std::wstringwsValueLcpprestsdkgithub;voidOfficialExample(conststd::wstringwsServersite,conststd::wstringwsURI,conststd::wstringwsURIName,conststd::wstringwsURIValue){autofileStreamstd::makesharedostream();Openstreamtooutputfile。pplx::taskvoidrequestTaskfstream::openostream(U(。。x64results。html))。then(〔〕(ostreamoutFile){fileStreamoutFile;Createhttpclienttosendtherequest。httpclientclient(wsServersite);wsServersitehttp:www。bing。comBuildrequestURIandstarttherequest。uribuilderbuilder(wsURI);builder。appendquery(wsURIName,wsURIValue);std::wstrings1builder。tostring()。cstr();std::wcouts1std::endl;returnclient。request(methods::GET,builder。tostring());})Handleresponseheadersarriving。。then(〔〕(httpresponseresponse){printf(Receivedresponsestatuscode:u,response。statuscode());Writeresponsebodyintothefile。returnresponse。body()。readtoend(fileStreamstreambuf());})Closethefilestream。。then(〔〕(sizet){returnfileStreamclose();});WaitforalltheoutstandingIOtocompleteandhandleanyexceptionstry{requestTask。wait();}catch(conststd::exceptione){printf(Errorexception:s,e。what());}}intmain(intargc,charargv〔〕){官方示例测试std::wstringwsServersiteLhttp:www。bing。com;std::wstringwsURILsearch;std::wstringwsNameLq;std::wstringwsValueLcpprestsdkgithub;OfficialExample(wsServersite,wsURI,wsName,wsValue);}
官方代码用的C11新特性。then实现的异步请求,如果不适应的话可以改为同步请求数据:voidOfficialExample(){autofileStreamstd::makesharedostream();ostreamoutFilefstream::openostream(U(results。html))。get();fileStreamoutFile;Createhttpclienttosendtherequest。httpclientclient(U(http:www。bing。com));BuildrequestURIandstarttherequest。uribuilderbuilder(U(search));builder。appendquery(U(q),U(cpprestsdkgithub));httpresponseresponseclient。request(methods::GET,builder。tostring())。get();Writeresponsebodyintothefile。response。body()。readtoend(fileStreamstreambuf())。get();fileStreamclose()。get();}3、使用自己的后台api接口进行验证,包括添加header
1)POST接口使用:includestdafx。hincludecppresthttpclient。hincludecpprestfilestream。husingnamespaceutility;Commonutilitieslikestringconversionsusingnamespaceweb;CommonfeatureslikeURIs。usingnamespaceweb::http;CommonHTTPfunctionalityusingnamespaceweb::http::client;HTTPclientfeaturesusingnamespaceconcurrency::streams;AsynchronousstreamsvoidTestPostRequest(conststd::wstringwsServersite,conststd::wstringwsURI,conststd::wstringuserName,conststd::wstringpassWord){utility::stringstreamtmsgStream;try{json::valuereqMsg;reqMsg〔U(userName)〕json::value::string(userName);reqMsg〔U(userPassword)〕json::value::string(passWord);reqMsg。serialize(msgStream);}catch(conststd::exceptione){std::cerre。what();return;}try{defaulttimeoutis30s,setto10shttpclientconfigconfig;config。settimeout(utility::seconds(10));Createhttpclienttosendtherequest。httpclientclient(wsServersite);BuildrequestURIandstarttherequest。uribuilderbuilder(wsURI);request,同步方式httprequestRequest(methods::POST);Request。headers()。add(LAuthorization,LBearercn5f6c09ce2d534146b6d445c338da581d);Request。setrequesturi(builder。tostring());Request。setbody(msgStream。str(),U(applicationjson));request,同步方式httpresponseresponseclient。request(Request)。get();httpresponseresponseclient。request(methods::POST,builder。tostring(),msgStream。str(),U(applicationjson))。get();if(response。statuscode()statuscodes::OK){try{从返回的json中获取字段值constjson::valuejvresponse。extractjson()。get();constweb::json::objectjobjjv。asobject();autoresultcodejobj。at(U(code))。asinteger();std::wstringresultmsgjobj。at(U(msg))。asstring()。cstr();std::wcout。imbue(std::locale(chs));std::wcoutcode:resultcode;msg:resultmsgstd::endl;输出返回的所有json内容std::wstringresultmsgresponse。extractstring()。get();std::wcout。imbue(std::locale(chs));std::wcoutresultmsg:resultmsgstd::endl;}catch(conststd::exceptione){std::wcoute。what()std::endl;}}else{std::wcouterror:response。statuscode()std::endl;}}catch(conststd::exceptione){std::cerre。what();}}intmain(intargc,charargv〔〕){测试POST接口std::wstringuserNameLadmin;std::wstringpasswordL123456;std::wstringwsServersiteLhttp:10。31。222。162:80;std::wstringwsURILauthweblogin;TestPostRequest(wsServersite,wsURI,userName,password);}
2)Get接口使用:includestdafx。hincludecppresthttpclient。hincludecpprestfilestream。husingnamespaceutility;Commonutilitieslikestringconversionsusingnamespaceweb;CommonfeatureslikeURIs。usingnamespaceweb::http;CommonHTTPfunctionalityusingnamespaceweb::http::client;HTTPclientfeaturesusingnamespaceconcurrency::streams;AsynchronousstreamsvoidTestGetRequest(conststd::wstringwsServersite,conststd::wstringwsURI,conststd::wstringwsURIName,conststd::wstringwsURIValue){Openstreamtooutputfile。try{defaulttimeoutis30s,setto10shttpclientconfigconfig;config。settimeout(utility::seconds(10));Createhttpclienttosendtherequest。httpclientclient(wsServersite);BuildrequestURIandstarttherequest。uribuilderbuilder(wsURI);builder。appendquery(wsURIName,wsURIValue);AddHeaderhttprequestRequest(methods::GET);Request。headers()。add(Lxuserid,L69003613);Request。headers()。add(LAuthorization,LBearercn45c338da581d);Request。setrequesturi(builder。tostring());request,同步方式httpresponseresponseclient。request(Request)。get();if(response。statuscode()statuscodes::OK){输出返回的所有json内容std::wstringresultmsgresponse。extractstring()。get();std::wcout。imbue(std::locale(chs));std::wcoutresultmsg:resultmsgstd::endl;}else{std::wcouterror:response。statuscode()std::endl;}}catch(conststd::exceptione){printf(Errorexception:s,e。what());}}intmain(intargc,charargv〔〕){std::wstringwsServersiteLhttp:10。31。222。162:80;std::wstringwsURILmessagprojectscount;std::wstringwsNameLprojectId;std::wstringwsValueLa6a6aa80bfaf412;TestGetRequest(wsServersite,wsURI,wsName,wsValue);return0;}4、cppRestSdk编译包及示例源码下载
本人采用了vc141编译cppRestSdk包,可以支持VS2015VS2017VS2019的使用,包含:include、lib、dll文件夹,提供x64位debug和release编译结果。如有兴趣可以去下载,下载地址:https:download。csdn。netdownloadm03725175086903716;
逆向思维怎么改变自己的命运,你只需要做到简单一点逆向思维如何改变自己的命运,你只需要做到简单一点。古人讲,知人者智,自知者明,以铜为镜可以正衣冠,以人为镜可以明得失。人贵有自知之明,一个人看透别人容易,能清醒认识自己,看透自己才
一个人给你聊这三个隐私,是真的爱上你了图来自网络,侵权请联系删除爱情虚无缥缈,但又有据可依,但凡他爱上了你,就会露出蛛丝马迹,也能让你心动不已。有些人之所以会错过爱情,不是因为对方不够爱,而是两人都支支吾吾,既没有表白
男女之间,一旦付出了真爱,这一辈子都忘不掉了!爱情的幸福在哪里,爱情的渴望是什么,一切看似很简单的,一切看似很幸福的事情,就是你可以拥有无限期待的美好。当你深度的探索到爱情的时候,深度拥有爱情的时候,你就知道生活的价值在哪里了
关于我的爱情观00后的我们处在一个浮躁,快的时代的集合点,社会发展快速,致使代际之间矛盾,冲突,同样的时代的经济,政治也决定文化,爱情观何尝不属于文化一部分呢。反而在这个快餐时代盛行的时代我反而
错的是选择,爱没有错错的是选择,爱没有错错的是缘分,无情的不是人,是距离。宫崎骏说你要相信,世上总有一个人,愿意用最朴素的方式喜欢你,不是撩,也不是套路,就是单纯的想对你好,忍不住的那种。今年最大的改
平凡中的不平凡整整三年,不知经历了多少痛苦和纠缠,才做出来的选择,两害相权取其轻。也许就像生活,只有亲生经历过的人,才能真正明白其中的苦与甜,疫情放开后的第一个周,朋友圈里各种晒,让人有点胆战心
旅游业疯狂宰客,就是自取灭亡!据携程报告春节期间,三亚酒店单间一夜价格最高达到20万元以上。涨价幅度之大堪称历史之最。例如三亚亚龙湾海棠湾的豪华型度假酒店,基本已经没有低于每晚4000元的价格位置好些的高档型酒
阳光下诚信经营合规中快速发展阳光人寿潍坊中支近日召开风控合规条线会议,各部门本部营业区合规负责人现场参会,各郊县机构合规负责人线上参会。会上,中支风控合规负责人总结通报了2022年度风控合规工作执行情况,着重
喧嚣的生活不代表充实,独舞的感觉也并不孤独席慕蓉说我一生的种种努力,不过只为了让周遭的人对我满意,为了博得亲人朋友的认同和赞许,我战战兢兢地将自己套入模式,桎梏,走到中途发现,我只剩下一副模糊的面目和一条回不去头的路。有人
科尔疲劳不是输球原因昨天休息了ampampamp水花的上场时间是正常的直播吧2月2日讯勇士今日客战114119加时不敌森林狼。赛后,有记者问科尔疲劳是否是球队输球的原因?对此科尔回答说不,不,比赛打了加时,库里和克莱打了42和40分钟,你把加时去掉,
时代的巨变2014年前后的大转变,你是否感觉到?2014年,这是个不平凡的一年。社会的变化,让我们感受到了什么是后工业文明时代。这一年,是马年。也是两位姓马的人物时代。一位,值得肯定的是,他创造的电商帝国,改变了我们每个国人的生