安装 C++ REST SDK

  1. $ brew install cpprestsdk
  2. $ brew install boost
  3. $ brew install libressl

创建工程

打开 Xcode,File / New / Project...

在向导的第1页选 macOS / Command Line Tool

在向导的第2页语言选 C++,Product Name 填上任意名称

在向导的第3页选择任意文件夹,点击 Create 创建工程。

配置工程

将 System Header Search Paths 设置为

/usr/local/Cellar/cpprestsdk/2.10.2/include

/usr/local/Cellar/boost/1.67.0_1/include

/usr/local/Cellar/libressl/2.7.4/include

将 Library Search Paths 设置为

/usr/local/Cellar/cpprestsdk/2.10.2/lib

/usr/local/Cellar/boost/1.67.0_1/lib

/usr/local/Cellar/libressl/2.7.4/lib

将 Other Linker Flags 设置为

-lcpprest -lboost_system -lboost_thread-mt -lboost_chrono-mt -lssl -lcrypto

cpprestsdk: Undefined symbols for architecture x86_64

示例代码1

  1. #include <cpprest/http_client.h>
  2. #include <cpprest/filestream.h>
  3. using namespace utility; // Common utilities like string conversions
  4. using namespace web; // Common features like URIs.
  5. using namespace web::http; // Common HTTP functionality
  6. using namespace web::http::client; // HTTP client features
  7. using namespace concurrency::streams; // Asynchronous streams
  8. int main(int argc, char* argv[])
  9. {
  10. auto fileStream = std::make_shared<ostream>();
  11. // Open stream to output file.
  12. pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile) {
  13. *fileStream = outFile;
  14. // Create http_client to send the request.
  15. http_client client(U("http://www.bing.com/"));
  16. // Build request URI and start the request.
  17. uri_builder builder(U("/search"));
  18. builder.append_query(U("q"), U("cpprestsdk github"));
  19. return client.request(methods::GET, builder.to_string());
  20. })
  21. // Handle response headers arriving.
  22. .then([=](http_response response) {
  23. printf("Received response status code:%u\n", response.status_code());
  24. // Write response body into the file.
  25. return response.body().read_to_end(fileStream->streambuf());
  26. })
  27. // Close the file stream.
  28. .then([=](size_t) {
  29. return fileStream->close();
  30. });
  31. // Wait for all the outstanding I/O to complete and handle any exceptions
  32. try {
  33. requestTask.wait();
  34. } catch (const std::exception &e) {
  35. printf("Error exception:%s\n", e.what());
  36. }
  37. return 0;
  38. }

这段代码访问

http://www.bing.com/search?q=cpprestsdk github

将结果保存为 results.html。

JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。

以下使用 C++ REST SDK 调用该网站的 REST API,获取字符串以及 JSON 数据。

  • GET /posts/1
  • GET /posts
  • POST /posts
  • PUT /posts/1
  • DELETE /posts/1

所有 GET API 都返回JSON数据,格式(JSON-Schema)如下:

  1. {
  2. "type":"object",
  3. "properties": {
  4. "userId": {"type" : "integer"},
  5. "id": {"type" : "integer"},
  6. "title": {"type" : "string"},
  7. "body": {"type" : "string"}
  8. }
  9. }

示例代码2

  1. #include <cpprest/http_client.h>
  2. #include <cpprest/filestream.h>
  3. #include <cpprest/json.h>
  4. #include <boost/algorithm/string/replace.hpp>
  5. using namespace utility; // Common utilities like string conversions
  6. using namespace web; // Common features like URIs.
  7. using namespace web::http; // Common HTTP functionality
  8. using namespace web::http::client; // HTTP client features
  9. using namespace concurrency::streams; // Asynchronous streams
  10. using namespace std;
  11. static void print_results(json::value const & value)
  12. {
  13. if(!value.is_null()) {
  14. auto userId = value.at(U("userId")).as_integer();
  15. auto id = value.at(U("id")).as_integer();
  16. auto title = value.at(U("title")).as_string();
  17. auto body = boost::algorithm::replace_all_copy(value.at(U("body")).as_string(), "\n", "\\n");
  18. cout << "Post {userId = " << userId
  19. << ", id = " << id
  20. << ", title = \"" << title
  21. << "\", body = \"" << body
  22. << "\"}" << endl;
  23. }
  24. }
  25. static void json_get()
  26. {
  27. http_client client(U("https://jsonplaceholder.typicode.com/"));
  28. // Build request URI and start the request.
  29. uri_builder builder(U("posts/1"));
  30. client
  31. // send the HTTP GET request asynchronous
  32. .request(methods::GET, builder.to_string())
  33. // continue when the response is available
  34. .then([](http_response response) -> pplx::task<json::value> {
  35. // if the status is OK extract the body of the response into a JSON value
  36. // works only when the content type is application\json
  37. if(response.status_code() == status_codes::OK) {
  38. return response.extract_json();
  39. }
  40. // return an empty JSON value
  41. return pplx::task_from_result(json::value());
  42. })
  43. // continue when the JSON value is available
  44. .then([](pplx::task<json::value> previousTask) {
  45. // get the JSON value from the task and display content from it
  46. try {
  47. json::value const & v = previousTask.get();
  48. print_results(v);
  49. } catch (http_exception const & e) {
  50. printf("Error exception:%s\n", e.what());
  51. }
  52. })
  53. .wait();
  54. }
  55. static void json_post()
  56. {
  57. http_client client(U("https://jsonplaceholder.typicode.com/"));
  58. json::value json_v ;
  59. json_v["userId"] = json::value::number(101);
  60. json_v["title"] = json::value::string("test title");
  61. json_v["body"] = json::value::string("test body");
  62. client
  63. .request(methods::POST, U("posts"), json_v)
  64. .then([](http_response response) -> pplx::task<string_t> {
  65. if(response.status_code() == status_codes::Created) {
  66. return response.extract_string();
  67. }
  68. return pplx::task_from_result(string_t());
  69. })
  70. .then([](pplx::task<string_t> previousTask) {
  71. try {
  72. string_t const & v = previousTask.get();
  73. cout << v << endl;
  74. } catch (http_exception const & e) {
  75. printf("Error exception:%s\n", e.what());
  76. }
  77. })
  78. .wait();
  79. }
  80. static void json_update()
  81. {
  82. http_client client(U("https://jsonplaceholder.typicode.com/"));
  83. json::value json_v ;
  84. json_v["userId"] = json::value::number(101);
  85. json_v["title"] = json::value::string("test title");
  86. json_v["body"] = json::value::string("test body");
  87. client
  88. .request(methods::PUT, U("posts/1"), json_v)
  89. .then([](http_response response) -> pplx::task<string_t> {
  90. if(response.status_code() == status_codes::OK) {
  91. return response.extract_string();
  92. }
  93. return pplx::task_from_result(string_t());
  94. })
  95. .then([](pplx::task<string_t> previousTask) {
  96. try {
  97. string_t const & v = previousTask.get();
  98. cout << v << endl;
  99. } catch (http_exception const & e) {
  100. printf("Error exception:%s\n", e.what());
  101. }
  102. })
  103. .wait();
  104. }
  105. static void json_delete()
  106. {
  107. http_client client(U("https://jsonplaceholder.typicode.com/"));
  108. client
  109. .request(methods::DEL, U("posts/1"))
  110. .then([](http_response response) -> pplx::task<string_t> {
  111. if(response.status_code() == status_codes::OK) {
  112. return response.extract_string();
  113. }
  114. return pplx::task_from_result(string_t());
  115. })
  116. .then([](pplx::task<string_t> previousTask) {
  117. try {
  118. string_t const & v = previousTask.get();
  119. cout << v << endl;
  120. } catch (http_exception const & e) {
  121. printf("Error exception:%s\n", e.what());
  122. }
  123. })
  124. .wait();
  125. }
  126. int main(int argc, char* argv[])
  127. {
  128. json_get();
  129. json_post();
  130. json_update();
  131. json_delete();
  132. return 0;
  133. }

这段代码调用4个 REST API

然后打印所返回的 JSON 数据以及字符串的内容

  1. Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
  2. {
  3. "body": "test body",
  4. "title": "test title",
  5. "userId": 101,
  6. "id": 101
  7. }
  8. {
  9. "body": "test body",
  10. "title": "test title",
  11. "userId": 101,
  12. "id": 1
  13. }
  14. {}

使用 C++ REST SDK 进行网络编程的更多相关文章

  1. Java Socket网络编程的经典例子(转)

    事实上网络编程简单的理解就是两台计算机相互通讯数据而已,对于程序员而言,去掌握一种编程接口并使用一种编程模型相对就会显得简单的多了,Java SDK提供一些相对简单的Api来完成这些工作.Socket ...

  2. iOS网络编程模型

    iOS网络编程层次结构也分为三层: Cocoa层:NSURL,Bonjour,Game Kit,WebKit Core Foundation层:基于 C 的 CFNetwork 和 CFNetServ ...

  3. 物联网网络编程、Web编程综述

    本文是基于嵌入式物联网研发工程师的视觉对网络编程和web编程进行阐述.对于专注J2EE后端服务开发的童鞋们来说,这篇文章可能稍显简单.但是网络编程和web编程对于绝大部分嵌入式物联网工程师来说是一块真 ...

  4. 有哪些适合学生参与的 C++,网络编程方面的开源项目?

    有哪些适合学生参与的 C++,网络编程方面的开源项目?   Tinyhttpd是一个超轻量型Http Server,使用C语言开发,全部代码只有502行(包括注释),附带一个简单的Client,可以通 ...

  5. windows socket 网络编程

    样例代码就在我的博客中,包含六个UDP和TCP发送接受的cpp文件,一个基于MFC的局域网聊天小工具project,和此小工具的全部执行时库.资源和执行程序.代码的压缩包位置是http://www.b ...

  6. 初识Java网络编程

    事实上网络编程简单的理解就是两台计算机相互通讯数据而已,对于程序员而言,去掌握一种编程接口并使用一种编程模型相对就会显得简单的多了,Java SDK提供一些相对简单的Api来完成这些工作.Socket ...

  7. Android开发学习之路--网络编程之初体验

    一般手机都是需要上网的,一般我们的浏览器就是个webview.这里简单实现下下功能,先编写Android的layout布局: <?xml version="1.0" enco ...

  8. 网络编程懒人入门(八):手把手教你写基于TCP的Socket长连接

    本文原作者:“水晶虾饺”,原文由“玉刚说”写作平台提供写作赞助,原文版权归“玉刚说”微信公众号所有,即时通讯网收录时有改动. 1.引言 好多小白初次接触即时通讯(比如:IM或者消息推送应用)时,总是不 ...

  9. Python_socket常见的方法、网络编程的安全注意事项、socketsever模块、浏览器中在一段时间记录用户的登录验证机制

    1.socket常见的方法 socket_常见方法_服务器端 import socket from socket import SOL_SOCKET,SO_REUSEADDR sk = socket. ...

随机推荐

  1. windows的docker开始支持linux的镜像 ,Version 18.03.0-ce-win59 (16762)

    LCOW containers can now be run next to Windows containers.Use '--platform=linux' in Windows containe ...

  2. 剑指Offer 43. 左旋转字符串 (字符串)

    题目描述 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果.对于一个给定的字符序列S,请你把其循环左移K位后的序列输出.例如,字符序列S=&quo ...

  3. React Native Android打包apk

    按照官方的5步曲: 1.在终端里面,cd 到项目的根目录后.执行下面这行命令: keytool -genkey -v -keystore my-release-key.keystore -alias ...

  4. 关于attibutedText输出中文字符后的英文和数字进行分开解析的问题

    上面的图应该很清楚 具体这个attibutedText 是做什么的就不说了 ,最初我查了资料发现有人和我一样的输出,把一个字符串的中英文分开打印出来是iOS关于UItextVIew和UIlabel的差 ...

  5. 使用Ajax+jQuery来实现前端收到的数据在console上显示+简单的主页设计与bootstrap插件实现图片轮播

    1.实现前端输入的数据在console上显示 上一篇是解决了在前端的输入信息在cygwin上显示,这次要给前台们能看见的数据,因为数据库里插入的数据少,所以写的语句翻来覆去就那几个词,emmm···当 ...

  6. leetcode 846.Hand of Straights

    对于一个数组中的数分为W组且在每一组内的数是连续存在的. 考虑使用map映射来记录每个数的个数的,并且对于数组中的数进行从小到大的排列的.同时每次需要更新最开始的那个起始数的,可能是以及出现的也可能是 ...

  7. 渲染标签 - v-text

    <!DOCTYPE html><html><head>    <meta charset="utf-8">    <title ...

  8. matplotlib.pyplot展示MNIST图片

    import torch import torch.utils.data as Data import torchvision import torchvision.transforms as tra ...

  9. IIS发布错误及解决

    HTTP 错误 403.14 - Forbidden  解决办法: 打开iis管理器,找到对应网站,并找到目录浏览,双击打开. 点击启用即可. HTTP 错误 500.19 - Internal Se ...

  10. (思维导图搞定)Content-Type:application/json,后台如何接收

    自己定的规范:只要Content-Type设置为application/json的时候,前台的data要传递字符串 虽然设置为application/json,前台传对象request.getPara ...