1

I'm new to c++ and visual c++ and working on accessing api using cpprestsdk aka casablanca.

I managed to follow the tutorial from its github and able to display the return data in terminal.

But I don't know how to display specific data. The return data is of json format.

This is my code:

#include "stdafx.h"

#include <iostream>

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

//using namespace std;

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());
        stringstreambuf buffer;
        response.body().read_to_end(buffer).get();



        printf("Response body: \n %s", buffer.collection().c_str());

        return  fileStream->print(buffer.collection()); //write to file anyway
    })

        // 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;
}

The return data from api:

{
"data":{
    "sch_time_setting":[{
        "holiday":["Saturday","Friday"],
        "biweekly_odd":[],
        "biweekly_even":["Saturday"],
        "clock_in_mon":"08:40",
        "clock_in_tue":"08:40",
        "clock_in_wed":"08:40",
        "clock_in_thu":"08:40",
        "clock_in_fri":"08:40",
        "clock_in_sat":"08:40",
        "clock_in_sun":null,
        "clock_in_hol":null,
        "clock_out_mon":"18:00",
        "clock_out_tue":"18:00",
        "clock_out_wed":"18:00",
        "clock_out_thu":"18:00",
        "clock_out_fri":"18:00",
        "clock_out_sat":"18:00",
        "clock_out_sun":null,
        "clock_out_hol":null,
        "_id":"5a9797b480591678e077118f"
    }],
    "_id":"5a9797b480591678e0771190",
    "staff_id":172,
    "temp_name":"Regular Employment",
    "individual_setting":false,
    "employment_category":"Regular Employee",
    "branch_office":"Cebu Branch Office",
    "availability_status":"Incumbent",
    "req_working_hours":"08:00",
    "fixed_brk_time_from":"12:00",
    "fixed_brk_time_to":"13:00",
    "date_to_start":"2018-03-01T06:03:32.050Z",
    "createdAt":"2018-03-01T06:03:32.066Z",
    "updatedAt":"2018-03-01T06:03:32.066Z",
    "__v":0
    },
"success":true
}
noyruto88
  • 767
  • 2
  • 18
  • 40

1 Answers1

1

Define a web::json::value variable to take the json response from the response.

web::json::value response;

Now, once the request returns the response and the return code is OK, then you can extract json from it using extract_json(). Something like this

.then([&response](http_response _response){
        if (_response.status_code() == web::http::status_codes::OK) {

            response = _response.extract_json().get();
        }
}

Now, you should be able to do json operations on the response, by using response.as_object() or auto id = response[L"data"][L"_id"].as_string(); etc.

Wander3r
  • 1,801
  • 17
  • 27
  • Hi sir, I tried to output auto id = response[L"data"][L"_id"].as_string(); in the console, but it doesn't show any data. – noyruto88 Apr 20 '18 at 05:48
  • `response[L"data"][L"_id"].as_string()` converts to STL `string`. Try ouputting using `.c_str()` with `std::wcout << j[L"data"][L"_id"].as_string().c_str() << std::endl;` When I tried, it prints `"5a9797b480591678e0771190"` – Wander3r Apr 23 '18 at 08:18