weixin_46027762 2023-12-04 10:35 采纳率: 65.7%
浏览 31
已结题

c++ http服务器

我想写一个c++http服务器,能够创建接口,接受post数据内容,能够和java通过http协议进行交互

  • 写回答

16条回答 默认 最新

  • Oo1101oO 2023-12-04 11:02
    关注

    cpp-httplib这个库很好用,直接包含头文件就可以了,这里有例子,直接可以拿来用:
    https://github.com/yhirose/cpp-httplib.git

    #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);
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

问题事件

  • 系统已结题 12月14日
  • 已采纳回答 12月6日
  • 创建了问题 12月4日