说明:

cpp-httplib 是个开源的库,是一个c++封装的http库,使用这个库可以在linux、windows平台下完成http客户端、http服务端的搭建,这是一个多线程“阻塞”HTTP 库。
使用起来非常方便,只需要包含头文件httplib.h即可。
源码库地址:GitHub - yhirose/cpp-httplib: A C++ header-only HTTP/HTTPS server and client library

httplib 库基本结构:

发送请求Request类的组成:

class Request
{
	std::string method;  // 请求方法
	std::string path; // 请求路径
	map<std::string, std::string> param;  // 查询字符串(查询字符串中)
	map<std::string, std::string> headers;// 键值对头部
	std::string body; //正文
};

响应数据类Response的组成:

class Response
{
	int status; //返回的状态码
	map<std::string,std::string> headers; //返回的价值对头部
	std::string body; //正文
};

服务端Server 类的组成:

class Server {
public:
  using Handler = std::function<void(const Request &, Response &)>;
  using HandlerWithContentReader = std::function<void(
      const Request &, Response &, const ContentReader &content_reader)>;
  using Expect100ContinueHandler =
      std::function<int(const Request &, Response &)>;

  Server();

  virtual ~Server();

  virtual bool is_valid() const;

  Server &Get(const char *pattern, Handler handler);
  Server &Post(const char *pattern, Handler handler);
  Server &Post(const char *pattern, HandlerWithContentReader handler);
  Server &Put(const char *pattern, Handler handler);
  Server &Put(const char *pattern, HandlerWithContentReader handler);
  Server &Patch(const char *pattern, Handler handler);
  Server &Patch(const char *pattern, HandlerWithContentReader handler);
  Server &Delete(const char *pattern, Handler handler);
  Server &Delete(const char *pattern, HandlerWithContentReader handler);
  Server &Options(const char *pattern, Handler handler);

客户端Client 类的组成:

class Client
{
	//创建client
	Client(host,port);
	Get()
	Post()
	Put()
	...
};

简单实例:

Server:

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
// HTTP
httplib::Server svr;
// HTTPS
httplib::SSLServer svr;
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  res.set_content("Hello World!", "text/plain");
});
svr.listen("0.0.0.0", 8080);

Client:

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
// HTTP
httplib::Client cli("http://cpp-httplib-server.yhirose.repl.co");
// HTTPS
httplib::Client cli("https://cpp-httplib-server.yhirose.repl.co");
auto res = cli.Get("/hi");
res->status;
res->body;

SSL Support:

SSL support 要用到 CPPHTTPLIB_OPENSSL_SUPPORT. libssl and libcrypto 的支持。
现在只有 httplib 1.1.1 支持ssl 服务器。

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
// Server
httplib::SSLServer svr("./cert.pem", "./key.pem");
// Client
httplib::Client cli("https://localhost:1234"); // scheme + host
httplib::SSLClient cli("localhost:1234"); // host
// Use your CA bundle
cli.set_ca_cert_path("./ca-bundle.crt");
// Disable cert verification
cli.enable_server_certificate_verification(false);

g++ -o service service.cpp -I/usr/local/openssl/include -L/usr/local/openssl/lib -lssl -lcrypto -pthread

完整简单web例子:

#include <stdio.h>
#include <iostream>

#include <jsoncpp/json/json.h>
#include "httplib.h"

using namespace httplib;
using namespace std;

int g_val = 100;
void Get_CallBackFunc(const Request& req, Response& resp)
{
    printf("%d\n", g_val);
    cout << req.method << endl; 
    printf("i am Get_CallBackFunc\n");

    const char* lp = "<html><h2>hello bite!</h2></html>";
    resp.set_content(lp, strlen(lp), "text/html");
}

int main()
{
    Server http_svr;
    int a = 10;
    http_svr.Get("/abc", Get_CallBackFunc);
    http_svr.Post("/login", [](const Request& req, Response& resp){
            cout << req.body << endl;

            Json::Value resp_json;
            resp_json["login_status"] = true;
            Json::FastWriter w;
            resp.body = w.write(resp_json);

            resp.set_header("Content-Type", "application/json");
            });
    http_svr.set_mount_point("/", "./web");
    http_svr.listen("0.0.0.0", 21010);
    return 0;
}

完整简单upload例子:

#include "httplib.h"
#include <iostream>
#include <fstream>

using namespace httplib;
using namespace std;

int main(void)
{
    Server svr;
    svr.Post("/post", [](const Request &req, Response &res) {
        auto music_file = req.get_file_value("music_file");

        cout << "image file length: " << music_file.content.length() << endl
             << "image file name: " << music_file.filename << endl;
        {
            ofstream ofs(music_file.filename, ios::binary);
            ofs << music_file.content;
        }
        res.set_content("done", "text/plain");
    });
    svr.set_mount_point("/", "./www");
    /// listen
    svr.listen("0.0.0.0", 9089);
}

到此这是 httplib 的最基本的使用,要想熟练使用,还是需要多看更多的官方文档,谢谢大家。

转载:

https://www.csdn.net/tags/MtTaMg4sODA4NTMwLWJsb2cO0O0O.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐