Jim Griesmer
Jim Griesmer

Reputation: 23

Basic STL string extraction from results obtained from CPPRest libraries (i.e. casablanca)?

I'm trying to learn 2 things: 1) Some basic C++ STL (I'm an old C/C++ coder, trying to learn new stuff) 2) How to access my wunderlist account through REST services using the CPPRest library.

I have been able to successfully start an oauth2 process with Wunderlist, but to help me understand what's happening and being returned, all I want to do is print result strings. For the life of me, I can't figure out how to do this. It has something to do with manipulating iostreams, but since I'm new to these, I'm struggling.

Here's a code snippet that successfully gets HTML from an initial Wunderlist response into a streambuf, but I cannot get it into a string for printing (or whatever). Please note that I'm not concerned with doing this asynchronously; therefore, I'm just forcing synchronization via !task.is_done(). Also, if you want to compile and run you'd need to provide your own client_id for Wunderlist, OR use a different service.

#include "stdafx.h"
#include <cpprest/http_client.h>
#include <cpprest/oauth2.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
using namespace web::http::oauth2::details;

int main()
{
    http_client clientWL(U("https://www.wunderlist.com"));
    uri_builder builderWL(U("oauth/authorize"));
    builderWL.append_query(U("client_id"), U("[myclientid]"));
    builderWL.append_query(U("redirect_uri"), U("http://www.google.com"));
    builderWL.append_query(U("state"), U("Randomish"));

    auto task = clientWL.request(methods::GET, builderWL.to_string());
    while (!task.is_done());

    http_response resp1 = task.get();
    Concurrency::streams::basic_ostream<char> os = Concurrency::streams::container_stream<std::string>::open_ostream();
    Concurrency::streams::streambuf<char> sb = os.streambuf();

    Concurrency::task<size_t> task2 = resp1.body().read_to_end(sb);
    while (!task2.is_done());

    // HOW DO I GET THE RESULTING HTML STRING I CAN PLAINLY SEE IN sb 
    // (VIA A DEBUGGER) INTO THE FOLLOWING STRING OBJECT?
    std::string strResult;

    return 0;
}

Upvotes: 0

Views: 1023

Answers (1)

huu
huu

Reputation: 7482

There's a platform independent way of extracting the string from the http_response object:

http_response resp1 = task.get();
auto response_string = resp1.extract_string().get();
std::cout << response_string << std::endl; // Will print it to stdout

Upvotes: 2

Related Questions