安装 C++ REST SDK

$ brew install cpprestsdk
$ brew install boost
$ 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

#include <cpprest/http_client.h>
#include <cpprest/filestream.h> using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>(); // Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile) {
*fileStream = outFile; // Create http_client to send the request.
http_client client(U("http://www.bing.com/")); // Build request URI and start the request.
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
}) // Handle response headers arriving.
.then([=](http_response response) {
printf("Received response status code:%u\n", response.status_code()); // Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
}) // Close the file stream.
.then([=](size_t) {
return fileStream->close();
}); // Wait for all the outstanding I/O to complete and handle any exceptions
try {
requestTask.wait();
} catch (const std::exception &e) {
printf("Error exception:%s\n", e.what());
} return 0;
}

这段代码访问

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)如下:

{
"type":"object",
"properties": {
"userId": {"type" : "integer"},
"id": {"type" : "integer"},
"title": {"type" : "string"},
"body": {"type" : "string"}
}
}

示例代码2

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/json.h>
#include <boost/algorithm/string/replace.hpp> using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams using namespace std; static void print_results(json::value const & value)
{
if(!value.is_null()) {
auto userId = value.at(U("userId")).as_integer();
auto id = value.at(U("id")).as_integer();
auto title = value.at(U("title")).as_string();
auto body = boost::algorithm::replace_all_copy(value.at(U("body")).as_string(), "\n", "\\n"); cout << "Post {userId = " << userId
<< ", id = " << id
<< ", title = \"" << title
<< "\", body = \"" << body
<< "\"}" << endl;
}
} static void json_get()
{
http_client client(U("https://jsonplaceholder.typicode.com/"));
// Build request URI and start the request.
uri_builder builder(U("posts/1")); client
// send the HTTP GET request asynchronous
.request(methods::GET, builder.to_string())
// continue when the response is available
.then([](http_response response) -> pplx::task<json::value> {
// if the status is OK extract the body of the response into a JSON value
// works only when the content type is application\json
if(response.status_code() == status_codes::OK) {
return response.extract_json();
} // return an empty JSON value
return pplx::task_from_result(json::value());
})
// continue when the JSON value is available
.then([](pplx::task<json::value> previousTask) {
// get the JSON value from the task and display content from it
try {
json::value const & v = previousTask.get();
print_results(v);
} catch (http_exception const & e) {
printf("Error exception:%s\n", e.what());
}
})
.wait();
} static void json_post()
{
http_client client(U("https://jsonplaceholder.typicode.com/")); json::value json_v ;
json_v["userId"] = json::value::number(101);
json_v["title"] = json::value::string("test title");
json_v["body"] = json::value::string("test body"); client
.request(methods::POST, U("posts"), json_v)
.then([](http_response response) -> pplx::task<string_t> {
if(response.status_code() == status_codes::Created) {
return response.extract_string();
}
return pplx::task_from_result(string_t());
})
.then([](pplx::task<string_t> previousTask) {
try {
string_t const & v = previousTask.get();
cout << v << endl;
} catch (http_exception const & e) {
printf("Error exception:%s\n", e.what());
}
})
.wait();
} static void json_update()
{
http_client client(U("https://jsonplaceholder.typicode.com/")); json::value json_v ;
json_v["userId"] = json::value::number(101);
json_v["title"] = json::value::string("test title");
json_v["body"] = json::value::string("test body"); client
.request(methods::PUT, U("posts/1"), json_v)
.then([](http_response response) -> pplx::task<string_t> {
if(response.status_code() == status_codes::OK) {
return response.extract_string();
}
return pplx::task_from_result(string_t());
})
.then([](pplx::task<string_t> previousTask) {
try {
string_t const & v = previousTask.get();
cout << v << endl;
} catch (http_exception const & e) {
printf("Error exception:%s\n", e.what());
}
})
.wait();
} static void json_delete()
{
http_client client(U("https://jsonplaceholder.typicode.com/")); client
.request(methods::DEL, U("posts/1"))
.then([](http_response response) -> pplx::task<string_t> {
if(response.status_code() == status_codes::OK) {
return response.extract_string();
}
return pplx::task_from_result(string_t());
})
.then([](pplx::task<string_t> previousTask) {
try {
string_t const & v = previousTask.get();
cout << v << endl;
} catch (http_exception const & e) {
printf("Error exception:%s\n", e.what());
}
})
.wait();
} int main(int argc, char* argv[])
{
json_get();
json_post();
json_update();
json_delete(); return 0;
}

这段代码调用4个 REST API

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

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"}
{
"body": "test body",
"title": "test title",
"userId": 101,
"id": 101
}
{
"body": "test body",
"title": "test title",
"userId": 101,
"id": 1
}
{}

使用 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. C# 注册机功能开发,机器码设计

    前言 本文将使用一个NuGet公开的组件技术来实现机器码注册码功能开发,提供了一些简单的API,来方便的实现. 在Visual Studio 中的NuGet管理器中可以下载安装,也可以直接在NuGet ...

  2. ELF文件加载与动态链接(一)

    关于ELF文件的详细介绍,推荐阅读: ELF文件格式分析 —— 滕启明.ELF文件由ELF头部.程序头部表.节区头部表以及节区4部分组成. 通过objdump工具和readelf工具,可以观察ELF文 ...

  3. latex之矩阵表示

    $ \begin{matrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1 \end{matrix}\quad \begin{ ...

  4. AFN 二次封装

    #import "YQDataManager.h" #import <YYModel/YYModel.h> #pragma mark - 数据model基类 @impl ...

  5. js基础概念-操作符

    操作符是操作数据值的符号,也叫做运算符. 按照操作个数分为:一元运算符,二元运算符,三元运算符. 按功能分为:位操作符,布尔操作符,乘性操作符,加性操作符,关系操作符,关系操作符,相等操作符,条件操作 ...

  6. Js高级 事件冒泡

    什么叫事件冒泡 当给父子元素的同一事件绑定方法时,触发了子元素身上的事件,执行完毕之后,也会触发父级元素的相同事件,这种传播机制叫事件冒泡. 取消事件冒泡 Event对象有个属性叫cancelBubb ...

  7. 在jsp中应如何避免,request.getContextPath();等get报错问题

    导致request中的大部分get方法无法获取,是因为没有依赖的jar包.就像这样.这里不仅仅有getContextPath()方法报错,如果存在这个问题,大部分的request方法都不可用. 解决这 ...

  8. windows openssh server 安装试用

    使用Windows的可能会知道win10 的已经包好了openssh 服务,但是对于其他机器win 7 windows 2008 ,就需要其他的方法了 还好powershell 团队开发了支持wind ...

  9. c# automapper 使用(一)

    一.最简单的用法 有两个类User和UserDto public class User { public int Id { get; set; } public string Name { get; ...

  10. php读取不到指定的php.ini配置

    新建启动脚本 启动时指定路径 解决方案一:修改  /etc/init.d/php-fpm 文件 1 # 在这行命令上添加 指定的配置路径 2 php_opts="--fpm-config $ ...