c++restcpprest-sdk

How to retrieve bearer token from header (rest sdk)


I have worked a few times with a REST SDK. I want to retrieve a Bearer token from the response headers, using C++.

Image from Postman: image

I have tried this:

CMyClass::SomeMethod(const web::http::http_request& Request)
{
    const web::http::http_headers& headers = Request.headers();
    web::http::http_headers::const_iterator it = headers.find(web::http::header_names::authorization);
    if (it != headers.end())
    {
        std::cout << "+++\t" << it->first.c_str() << "\t" << it->second.c_str() << std::endl;
    }
}

but I only get this:

image

Which tells me that I have done something wrong.

So, how can I retrieve the Bearer token from web::http::http_request header?


Solution

  • The output you are seeing means that you are not passing char* string pointers to std::cout.

    Assuming you are using Microsoft's REST SDK (you did not say), its web::http::http_headers class holds utility::string_t values, and utility::string_t is defined as std::wstring on Windows (despite what the documentation says), not std::string like you are expecting.

    Which means you are passing wchar_t* string pointers to std:::cout, which does not have an operator<< for wchar_t*, but does have one for void*, hence the output you see.

    You would need to use std::wcout instead, or else convert the std::wstring data to std::string before printing it.