Search code examples
c++visual-c++cpprest-sdk

C++ REST SDK a.k.a Casablanka


How to cout or printf data return from api using c++ rest sdk aka casablanca?

I got this code from tutorial:

#include "stdafx.h"

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>

using namespace utility;                    // Common utilities like string conversions
using namespace web;                        // Common features like URIs.
using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features
using namespace concurrency::streams;       // Asynchronous streams

int main(int argc, char* argv[])
{
    auto fileStream = std::make_shared<ostream>();

    // Open stream to output file.
    pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
    {
        *fileStream = outFile;

        // Create http_client to send the request.
        http_client client(U("http://192.168.0.13:3000/api/individual_employment_setting/detail/172"));

        // Build request URI and start the request.
        //uri_builder builder(U("/search"));
        //builder.append_query(U("q"), U("cpprestsdk github"));
        return client.request(methods::GET);
    })

        // Handle response headers arriving.
        .then([=](http_response response)
    {
        printf("Received response status code:%u\n", response.status_code());

        // Write response body into the file.
        return response.body().read_to_end(fileStream->streambuf());
    })

        // Close the file stream.
        .then([=](size_t)
    {
        return fileStream->close();
    });

    // Wait for all the outstanding I/O to complete and handle any exceptions
    try
    {
        requestTask.wait();
    }
    catch (const std::exception &e)
    {
        printf("Error exception:%s\n", e.what());
    }

    return 0;
}

But it just write a file an .html file.

Is there a way to store the return data of api to a variable and just output it in terminal like cout or printf? Thanks.


Solution

  • You can try reading the response body with a string stream buffer, instead of the file stream buffer you're using right now:

        // Handle response headers arriving.
        .then([=](http_response response)
    {
        printf("Received response status code:%u\n", response.status_code());
    
        stringstreambuf buffer;
        response.body().read_to_end(buffer).get();
    
        //show content in console
        printf("Response body: \n %s", buffer.collection().c_str()); 
    
        //parse content into a JSON object:
        json::value jsonvalue = json::value::parse(buffer.collection());  
    
        //write content to file
        return  fileStream->print(buffer.collection());
    })