使用C++ REST SDK开发简单的Web(HTTP)服务

3 篇文章 0 订阅
2 篇文章 0 订阅
源地址:http://blog.csdn.net/ztsinghua/article/details/50977131
 

使用C++ REST SDK开发简单的Web(HTTP)服务

  1379人阅读  评论(0)  收藏  举报

C++ REST SDK是微软开源的一套客户端-服务器通信库,提供了URI构造/解析,JSON编解码,HTTP客户端、HTTP服务端,WebSocket客户端,流式传输,oAuth验证等C++类,方便C++语言编写的客户端程序访问互联网服务。其中HTTP服务端相关的类是最近新增的(尚处于beta测试阶段),这些类拓展了C++ REST SDK的功能,现在不仅能开发客户端程序,也能做服务端开发了。

获取C++ REST SDK:
目前C++ REST SDK源代码托管在github上,地址为:
https://github.com/Microsoft/cpprestsdk
可以用Git克隆或直接下载zip包

编译C++ REST SDK:
C++ REST SDK自带Visual Studio 2013及Visual Studio 2015解决方案文件,使用这两种IDE直接打开相应的解决方案即可。对于其它平台,可以用CMake生成该平台的MakeFile进行编译。编译C++ REST SDK还需要Boost和OpenSSL的开发文件,如果CMake提示找不到Boost或OpenSSL,则需要先行下载安装这几个库。
CMake: cmake.org
Boost: www.boost.org
OpenSSL: www.openssl.org

下面是一个简单的HTTP服务器程序,接收HTTP POST或GET请求,在控制台上打出请求的方法名,URI和查询参数,并返回"ACCEPTED"字符串。C++ REST SDK的API相当简明,无需注解应该可以看懂。

01 #include <stdio.h>
02 #include <cpprest/uri.h>
03 #include <cpprest/http_listener.h>
04 #include <cpprest/asyncrt_utils.h>
05  
06 #pragma comment(lib, "cpprest_2_7.lib")
07 #pragma comment(lib, "bcrypt.lib")
08 #pragma comment(lib, "crypt32.lib")
09 #pragma comment(lib, "winhttp.lib")
10 #pragma comment(lib, "httpapi.lib")
11  
12 using namespace web;
13 using namespace http;
14 using namespace utility;
15 using namespace http::experimental::listener;
16  
17 class CommandHandler
18 {
19 public:
20  CommandHandler() {}
21  CommandHandler(utility::string_t url);
22  pplx::task<void> open() { return m_listener.open(); }
23  pplx::task<void> close() { return m_listener.close(); }
24 private:
25  void handle_get_or_post(http_request message);
26  http_listener m_listener;
27 };
28  
29 CommandHandler::CommandHandler(utility::string_t url) : m_listener(url)
30 {
31  m_listener.support(methods::GET, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
32  m_listener.support(methods::POST, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
33 }
34  
35 void CommandHandler::handle_get_or_post(http_request message)
36 {
37  ucout << "Method: " << message.method() << std::endl;
38  ucout << "URI: " << http::uri::decode(message.relative_uri().path()) << std::endl;
39  ucout << "Query: " << http::uri::decode(message.relative_uri().query()) << std::endl << std::endl;
40  message.reply(status_codes::OK, "ACCEPTED");
41 };
42  
43 int main(int argc, char argv[])
44 {
45  try
46  {
47   utility::string_t address = U("http://*:8080");
48   uri_builder uri(address);
49   auto addr = uri.to_uri().to_string();
50   CommandHandler handler(addr);
51   handler.open().wait();
52   ucout << utility::string_t(U("Listening for requests at: ")) << addr << std::endl;
53   ucout << U("Press ENTER key to quit...") << std::endl;
54   std::string line;
55   std::getline(std::cin, line);
56   handler.close().wait();
57  }
58  catch (std::exception& ex)
59  {
60   ucout << U("Exception: ") << ex.what() << std::endl;
61   ucout << U("Press ENTER key to quit...") << std::endl;
62   std::string line;
63   std::getline(std::cin, line);
64  }
65  return 0;
66 }

以上代码在Visual Studio 2013下,用C++ REST SDK 2.7编译通过,运行正常,在Linux系统下也可以编译通过,但是需要链接不同的库,命令行为:
c++ -o restserver -std=C++11 restserver.cpp -lcpprest -lboost_system -lssl -lcrypto
测试服务器是否正常,可以用浏览器随便输入一个地址,例如http://localhost:8080/test?param=ok

需要注意的是,C++ REST SDK在Windows下,使用Windows系统自带的WinHTTP/HTTP Server API来实现HTTP协议通信,而在其它平台下是用Boost ASIO来实现HTTP协议通信,这两者的实际行为是有区别的,例如:
1.用C++ REST SDK编写HTTP客户端,当服务端返回响应码301/302时,Windows下会用新地址自动重发请求,而Linux下则不会(运行C++ REST SDK自带的BingRequest示例即可看到这一差异)。
2.用C++ REST SDK编写HTTP服务端,需要在所有的网络接口上监听时,Windows下应使用地址"http://*:8080",而Linux下应使用地址"http://0.0.0.0:8080"。

另外,在Windows下用C++ REST SDK开发HTTP服务时,还有两个坑需要注意:
第一,由于HTTP Server API自身的一些特性,当C++ REST SDK服务程序在localhost之外的地址上监听时,默认需要以管理员身份运行程序,如果以普通用户身份运行上面的小程序,则发生异常:
Exception: Access denied: attempting to add Address 'http://*:8080/'. Run as administrator to listen on an hostname other than localhost, or to listen on port 80.
如果不希望每次都以管理员身份运行,可以用以下命令开放普通用户的权限:
netsh http add urlacl url=http://*:8080/ user=BUILTIN\Users listen=yes
该命令本身要以管理员身份运行,在Windows 8.1系统下,用Win+X组合键打开“命令提示符(管理员)”,输入命令即可
第二:由于HTTP Server API内部用到了一个内核模块http.sys,C++ REST SDK服务程序通过Windows防火墙的方式和普通TCP服务程序不太一样,直接用程序的可执行文件建立防火墙规则是无效的。正确的方式是新建一个入站规则,程序名称设为system,并设置本地端口为想要监听的端口号。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值