一直苦恼在C++下没一个好用的http库,大众一点的就是curl了,以前也试用过它,阻塞的设计,每个线程只可以有一个句柄。。总之我觉得不好用
今天偶然发现了微软的一个开源项目Casablanca,试用了一下感觉棒极了,它使用了现在最前沿的C++11标准,写起代码来就是一个字:爽!
为了使用这么前卫的库,建议VS在2012以上。2010版以前貌似是用不了的。
先看看自己装了"NuGet程序包管理器"没有,没有则先装上它
然后进入安装包管理控制台
输入安装命令"install-package cpprestsdk"
稍等片刻后,最新版的rest sdk就安装好了,安装目录在"C:\Program Files (x86)\Microsoft SDKs\Cpp REST SDK for Visual Studio 2013"
后面就是新建工程,引入头文件和lib文件即可
#include "stdafx.h" #include <iostream> #include <http_client.h> #pragma comment(lib, "casablanca120.lib") using namespace std; using namespace web::http; using namespace web::http::client; int _tmain(int argc, _TCHAR* argv[]) { http_client cli(U("http://www.baidu.com")); // get方式请求服务 auto response = cli.request(methods::GET, U("s?wd=123")); // 指定一个回调函数,也就是匿名函数(lambda) auto task = response.then([](http_response hr) { cout << "error_code: " << hr.error_code() << endl; cout << "status code: " << hr.status_code() << endl; }); // 阻塞,等待请求完成 task.wait(); system("pause"); return 0; }
执行结果如图:
ps:C++11的auto真是个好东西有木有!?再也不怕那些名字又臭又长的类型了!