C++ REST SDK
一套用来开发HTTP客户端和服务器的现代异步C++代码库,支持以下特性:
- HTTP 客户端、HTTP服务端
- 任务
- JSON
- URI
- 异步流
- WebSocket 客户端
- OAuth 客户端
安装:https://blog.csdn.net/u014208472/article/details/70171597
编译
1
| g++ -std=c++17 -pthread test.cpp -lcpprest -lcrypto -lssl -lboost_thread -lboost_chrono -lboost_system
|
服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <exception> #include <iostream> #include <map> #include <string> #include <cpprest/http_listener.h> #include <cpprest/json.h>
void handle_get(web::http::http_request req) { auto& uri = req.request_uri(); if (uri.path() != U("/sayHi")) { req.reply(web::http::status_codes::NotFound); return; } std::cout << web::uri::decode(uri.query()) << std::endl; auto query = web::uri::split_query(uri.query()); auto it = query.find(U("name")); if (it == query.end()) { req.reply(web::http::status_codes::BadRequest, U("Missing query info")); return; } auto answer = web::json::value::object(true); answer[U("msg")] = web::json::value(utility::string_t(U("Hi, ")) + web::uri::decode(it->second) + U("!")); req.reply(web::http::status_codes::OK, answer); }
int main() { web::http::experimental::listener::http_listener listener(U("http://127.0.0.1:9999/")); listener.support(web::http::methods::GET, handle_get); try { listener.open().wait(); std::cout << "Listening. Press ENTER to exit.\n"; std::string line; getline(std::cin, line); listener.close().wait(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } }
|