Search code examples
c++restcpprest-sdkrestbed

Restbed: issue when i try to make a requst containing JSON parameter


Im fairly new to REST and i have tried to run basic tutorial code of Restbed that goes as follows:

#include <memory>
#include <cstdlib>
#include <restbed>

using namespace std;
using namespace restbed;

void get_method_handler( const shared_ptr< Session > session )
{
    session->close( OK, "Hello, World!", { { "Content-Length", "13" }, { "Connection", "close" } } );
}

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

    //auto ssl_settings = make_shared< SSLSettings >( );
    //ssl_settings->set_http_disabled( true );
    //ssl_settings->set_private_key( Uri( "file:///tmp/server.key" ) );
    //ssl_settings->set_certificate( Uri( "file:///tmp/server.crt" ) );
    //ssl_settings->set_temporary_diffie_hellman( Uri( "file:///tmp/dh768.pem" ) );

    auto settings = make_shared< Settings >( );
    //settings->set_ssl_settings( ssl_settings );

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

    return EXIT_SUCCESS;
}

Please note: the SSL init is commented out. When i make just a basic request (http://localhost/resource) everything is fine. With just a bit more complex request containing a parameter (http://localhost/resource?request=test) its still working as intended. When i try to pass in JSON object (http://localhost/resource?request={}) i get an error stating "Your client has issued a malformed or illegal request status line. That’s all we know.". I can get over this issue by running this command from Postman rather than browser but even then as soon as i change the command to http://localhost/resource?request={"test"=[]} it ends up with the same error again.

Can anyone shed a bit of light on what issue im looking at? Im running 64 bit windows 10, compiling the code in Visual Studio 2017.

Thank you in advance


Solution

  • It was a newbie mistake ofcourse :). Postman didnt encode the URL for me and it took me ages to realize that. I have used https://www.urlencoder.org/ to encode it and now it works fine.

    Unencoded example: {"values":["1", "2"]}
    Encoded example: %7B%22values%22%3A%5B%221%22%2C%20%222%22%5D%7D
    

    This article has opened my eyes: https://perishablepress.com/stop-using-unsafe-characters-in-urls/

    Edit: I should add that meanwhile i have learned that JSON object is much better sent as a body of the request with the header encoded as application/JSON.

    From my understanding the HTTP request cosists of URI - header and body. URI is the address requested (http://localhost:5000/test) header dictates the type and can contain data, body contains data that can be shadped based on the header (binary, json, text).