Installation and use of the httplib library

Table of contents

Install the httplib library

Know the httplib library

httplib request class

 httplib response class

 Server class in httplib       

The client class of httplib

The httplib library builds a simple server

The httplib library builds a simple client


Install the httplib library

1. Enter github and search for the httplib library

 2. Download library

3. After downloading, transfer the compressed package of the library to the Linux system

 4. Unzip the library

unzip cpp-httplib-master.zip

Know the httplib library

  • The httplib library, a C++11 single header cross-platform HTTP/HTTPS library.
  • The httplib library is actually used to build a simple http server or client library. This third-party network library can save us the time of building a server or client and devote more energy to specific business processing. Improve development efficiency .

httplib request class

  • The httplib request class is a request method that contains the request line in the http request, url, protocol version, and each response header value in the request header
namespace httplib{
    //文件信息结构体
    struct MultipartFormData {
        std::string name;        //字段名称
        std::string content;     //文件内容
        std::string filename;    //文件名称
        std::string content_type;//文件类型
   };
  using MultipartFormDataItems = std::vector<MultipartFormData>;

    struct Request {
        std::string method;  //请求方法
        std::string path;    //资源路径
        Headers headers;     //请求报头
        std::string body;    //请求正文
        // for server

        std::string version; //协议版本
        Params params;       //查询字符串
        MultipartFormDataMap files;//保存的是客户端上传的文件信息
        Ranges ranges;       //

        //判断请求报头中有没有 某个字段
        bool has_header(const char *key) const;
        //获取请求报头中对应的字段值
        std::string get_header_value(const char *key, size_t id = 0) const;
        //将key-val的字段值设定在http请求中
        void set_header(const char *key, const char *val);
        //判定是否有对应的文件
        bool has_file(const char *key) const;
        //获取对应的文件信息
        MultipartFormData get_file_value(const char *key) const;
   };

 httplib response class

The httplib class sets the response line, response header, and response body to the object of the Response class, and then organizes the Response object into an http response and sends it to the other party.

    struct Response {
        std::string version;   //协议版本号,默认时http1.1
        int status = -1;       //响应状态码,
        std::string reason;    
        Headers headers;       //响应报头
        std::string body;      //响应正文
        std::string location; // 重定向位置

//以key-val将相应的字段设定到响应报头中
 void set_header(const char *key, const char *val);
        void set_content(const std::string &s, const char *content_type);
   };

 Server class in httplib       


class Server {
        //Handler一个函数指针名称,它的参数是Request,和Response
        using Handler = std::function<void(const Request &, Response &)>;
        //Handlers是一个映射表,它映射对应的请求资源和处理函数映射在一起
        using Handlers = std::vector<std::pair<std::regex, Handler>>;
        //将Get方法的请求资源与处理函数加载到Handlers表中
        Server &Get(const std::string &pattern, Handler handler);
        Server &Post(const std::string &pattern, Handler handler);
        Server &Put(const std::string &pattern, Handler handler);
        Server &Patch(const std::string &pattern, Handler handler);  
        Server &Delete(const std::string &pattern, Handler handler);
        Server &Options(const std::string &pattern, Handler handler);
        //线程池
        std::function<TaskQueue *(void)> new_task_queue;

        //搭建并启动http
        bool listen(const char *host, int port, int socket_flags = 0);
 };

Handler table structure:

 As in the Handlers table above:

  • If the request method of the http request is the GET method and the requested resource is /hello, the server will call the Hello function to construct the corresponding http response.
  • If the request method of the http request is the POST method , and the requested resource is /Post, then the server will call the Post function to construct the corresponding http response.
  • If only does not exist in the Handlers table or does not match the Handlers table , the http server will return a 404 http response.
  • Get("/hello",Hello): Register the requester as GET, request resource /hello, and function Hello in the Handlers table
  • Post("/post",Post): Register the request method POST, request resource /post, and the function Post in the Handlers table

The work of the thread pool

  • When the server receives an http request , it put the http request into the thread pool, and the threads in the thread pool will call the corresponding function to parse the http request to form a Request class.
  • In the Handler mapping table, if there is a corresponding mapping function for the corresponding request method and request resource , the corresponding mapping function will be called and the http response will be constructed.
  • After the processing function is called, the constructed http response is sent to the client.

The client class of httplib

   class Client {
        //构造一个客户端对象,传入服务器Ip地址和端口
        Client(const std::string &host, int port);
        //向服务器发送GET请求
        Result Get(const char *path, const Headers &headers);
        //向服务器发送Post请求
        //path是路径,body是request请求路径
        //content_length是正文大小
        //content_type是正文的类型
        Result Post(const char *path, const char *body, size_t content_length,
              const char *content_type);
        
        //以Post方法上传文件
        Result Post(const char *path, const MultipartFormDataItems &items);
   }

The httplib library builds a simple server

Steps to build a server:

  • Use the httplib library to define server objects
  • Register the processing function of the request resource in the Handler table structure
  • Start the server with listen
   #include<iostream>    
  #include"httplib.h"    
  using namespace std;    
      
W>void Hello(const httplib::Request& req,httplib::Response& res){    
    res.set_content("Hello world","text/plain");    
    res.status=200;    
  }    
      
      
  void File(httplib::Request req,httplib::Response res){
    //获取字段为file的文件
    const auto& file=req.get_file_value("file");    
  
    std::cout<<file.filename<<endl;        
    std::cout<<file.content<<endl;    
  }    
      
  int main(){    
    httplib::Server server;//定义sercer对象    
    //注册处理函数    
    server.Get("/hi",Hello);    
    server.Post("/file",File);    
    server.listen("0.0.0.0",8081);//启动服务器    
    return 0;    
  }    

 

Notice:

  •  The Request parameter in the registration handler needs to be defined as const
  • Both the Request and Response parameters in the registration handler function need to be references, otherwise the browser will not accept the body content.

The httplib library builds a simple client

#include"httplib.h"    
#define IP "119.23.41.13"    
#define PORT 8081    
using namespace std;    
    
int main(){    
  //建立客户端对象    
  httplib::Client client(IP,PORT); 
  //单个文件信息组织   
  httplib::MultipartFormData file;    
  file.name="file";        
  file.content="hello world";    
  file.filename="Hello.txt";    
  file.content_type="text/plain";    
  
  //MultipartFormDataItems对象可以存储多个文件信息
  httplib::MultipartFormDataItems item;    
  item.push_back(file);    
  //请求服务器上/file资源,发送item文件集合给服务器
  auto result=client.Post("/file",item);     
  return 0;                                                                                                                                 
}    

 

 

 

Guess you like

Origin blog.csdn.net/sjp11/article/details/127990377