http

http

一,需求
Qt调用http接口,如果使用本身的network库需要做大量的工作,采用httplib这个库,则调用起来就特别优雅。

二,使用

  1. 这个库就是一个头文件,直接include进去即可。
    https://github.com/yhirose/cpp-httplib

  2. 看一个客户端列子。

    #include <httplib.h>
    #include <iostream>
    int main(void)
    {
    //定义客户端
    httplib::Client cli("localhost", 1234);
    
    //调用get接口
    if (auto res = cli.Get("/hi")) {
    if (res->status == StatusCode::OK_200) {
      std::cout << res->body << std::endl;
    }
    } else {
    auto err = res.error();
    std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
    }
    }

  3. 服务端写起来也很方便。

    #include <httplib.h>
    int main(void)
    {
    using namespace httplib;
    
    Server svr;
    
    svr.Get("/hi", [](const Request& req, Response& res) {
    res.set_content("Hello World!", "text/plain");
    });
    
    // Match the request path against a regular expression
    // and extract its captures
    svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
    auto numbers = req.matches[1];
    res.set_content(numbers, "text/plain");
    });
    
    // Capture the second segment of the request path as "id" path param
    svr.Get("/users/:id", [&](const Request& req, Response& res) {
    auto user_id = req.path_params.at("id");
    res.set_content(user_id, "text/plain");
    });
    
    // Extract values from HTTP headers and URL query params
    svr.Get("/body-header-param", [](const Request& req, Response& res) {
    if (req.has_header("Content-Length")) {
      auto val = req.get_header_value("Content-Length");
    }
    if (req.has_param("key")) {
      auto val = req.get_param_value("key");
    }
    res.set_content(req.body, "text/plain");
    });
    
    svr.Get("/stop", [&](const Request& req, Response& res) {
    svr.stop();
    });
    
    svr.listen("localhost", 1234);
    }
//客户端传图例子
QString file = QCoreApplication::applicationDirPath() + "/hf.jpg";
httplib::Client cli(ip, port);
cli.set_connection_timeout(0, 300000); // 300 milliseconds
cli.set_read_timeout(5, 0); // 5 seconds
cli.set_write_timeout(5, 0); // 5 seconds

std::ifstream sfile(file.toStdString().c_str(), std::ios::binary);
std::string imageData((std::istreambuf_iterator<char>(sfile)), std::istreambuf_iterator<char>());
httplib::MultipartFormDataItems items = {
{"file", imageData,  "hf.jpg", "application/octet-stream"},
};
auto res = cli.Post("/infer", items);
if (res&&res->status == 200)
{
		std::string body = res->body;
		std::cout << "上传成功: " << body;
}

发表回复