如何使用c ++语言和JSON Parser创建Restful Web服务

Rit*_*ati 23 c++ linux rest json web-services

我正在使用嵌入式Linux,我希望在我的Linux自定义板上运行Restful Web服务.

我的目标是向/从Web服务器(httpd服务器)发送/接收数据(采用JSON格式).

另外,我想使用C++语言创建Restful Web服务.

请参阅以下有关我的Linux自定义板需要Restful Web Services的想法.

  1. 首先,我将通过在我的linux板上运行的httpd服务器发送带有JSON格式数据的HTTP请求.

  2. 然后,我想创建一个二进制文件或服务器,用c ++语言实现这个Restful Web Services,用于处理HTTP请求.

  3. 然后,此C++二进制文件将响应发送回httpd服务器,以便通过Web浏览器显示.

有没有人有关于如何使用C++语言创建Restful Web Services的想法或示例?

欢迎任何有关Restful的帮助.

有没有人知道ffead及其功能是否满足我的Restful Web Services?

Ben*_*rst 22

除了JSON解析器之外,Restbed可以满足您的要求.但是,将解决方案与已有的许多C++ JSON实现之一相结合,只需要很少的工作.

#include <memory>
#include <string>
#include <cstdlib>
#include <sstream>
#include <jsonbox.h>
#include <restbed>

using namespace std;
using namespace restbed;

void get_method_handler( const shared_ptr< Session > session )
{
    const auto request = session->get_request( );

    size_t content_length = request->get_header( "Content-Length", 0 );

    session->fetch( content_length, [ ]( const shared_ptr< Session >& session, const Bytes& body )
    {
        JsonBox::Value json;
        json.loadFromString( string( body.begin( ), body.end( ) ) );

        //perform awesome solutions logic...

        stringstream stream;
        json.writeToStream( stream );
        string response_body = stream.str( );

        session->close( OK, response_body, { { "Content-Length", ::to_string( response_body.length( ) }, { "Content-Type": "application/json" } } );
    } );
}

int main( const int, const char** )
{
    auto resource = make_shared< Resource >( );
    resource->set_path( "/resource" );
    resource->set_method_handler( "GET", get_method_handler );

    auto settings = make_shared< Settings >( );
    settings->set_port( 1984 );
    settings->set_default_header( "Connection", "close" );

    Service service;
    service.publish( resource );
    service.start( settings );

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

替代RESTful框架

替代JSON框架

  • 是的,casablanca 是一个非常好的框架......它真的很完整,但是 SSL 对我的软件是一个限制,因此我改变了框架。是的,我玩过休息床......但是许可证“AGPL”对我不起作用......所以我认为最好的方法“POCO C++网络库”在我看来非常有用,你可以创建一个轻松使用 SSL 休息。我想知道你对此的看法。 (2认同)
  • 截至 2021 年,C++ REST SDK 可以认为已死!它的开发不再活跃,因此用户在使用它之前必须三思而后行。 (2认同)

The*_*ist 6

我知道这已经晚了,但一两年前已经出现了一些新的东西。

如果您热衷于高性能的核心异步编程,您可以考虑boost::beast它是boost::asio (通用 tcp/udp 和 i/o 库)之上的一层,具有 http(s) 和 websocket 服务器/客户端。

请记住,这些对于多线程的性能和完全自由来说是理想的选择(如果您有一台可以接受的服务器,您实际上可以在数千个线程上运行您的服务器,并且具有几乎完美的缓存),但它们有一个陡峭的学习曲线。仅当您需要绝对控制一切时才这样做!


Ser*_*tch 6

我将oatpp与nlohmann JSON结合使用。oatpp尽管您可能纯粹因为它具有内置的 JSON 处理功能而侥幸逃脱。请参阅分步指南

  • 你是如何将 nlohmann/json 与 oatpp 集成的?您是否将有效负载作为 oatpp::String 在 DTO 中传输,然后使用 nlohmann/json 解析它?或者直接将 nlohmann/json 对象包含为 DTO 的成员? (2认同)

dor*_*ron 1

也许您最好的选择是使用FastCGI创建一个模块来与您的 Web 服务器交互。这应该可以避免您必须实现自己的 HTTP 服务器。