Search code examples
c++casablancacpprest-sdk

http_client of cpprestsdk/casablanca


I have api https://api.gm-system.net/api/authenticate/searchStaffs/searchText which return a list staff.

And here is my code to access this api using cpprestsdk with c++.

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("https://api.gm-system.net/api/authenticate/searchStaffs/michael"));


        return client.request(methods::GET);
    })

        // Handle response headers arriving.
        .then([=](http_response response)
    {
       ......
    }

This one if fine. But with that i just manually input the "michael" searchText.

How can I make it that it will accept any searchText something like this.

void MyTest(std::string searchText)
{
..... code here

// Create http_client to send the request.
http_client client(U("https://api.gm-system.net/api/authenticate/searchStaffs/" + searchText));

return client.request(methods::GET);

..... code here
}

I already tried this it won't work. Some problem with 'U' macro. From https://github.com/Microsoft/cpprestsdk/wiki/FAQ the discription of U macro is says:

The 'U' macro can be used to create a string literal of the platform type. If you are using a library causing conflicts with the 'U' macro, for example Boost.Iostreams it can be turned off by defining the macro '_TURN_OFF_PLATFORM_STRING' before including the C++ REST SDK header files.

If I point my cursor to U, the error says:

no operator "+" matches these operands operand types are; const wchar_t[57] + const std::string

I hope some can help me. Thanks.


Solution

  • Since

    The C++ REST SDK uses a different string type dependent on the platform being targeted. For example for the Windows platforms utility::string_t is std::wstring using UTF-16, on Linux std::string using UTF-8.

    you should use the utility::string_t class whenever it is required and don't mix it with std::string or const char * (and use the U macro when in need of a literal).

    In other words, your function should accept an utility::string_t as its searchText argument (instead of std::string):

    void MyTest(utility::string_t searchText)
    {
        http_client client(U("https://api.gm-system.net/api/authenticate/searchStaffs/") + searchText);
    
        // etc ...
    
    }
    

    use it like this:

    int main()
    {
    
        utility::string_t searchText = U("Michael");
        MyTest(searchText);
    
        return 0;
    }
    

    If the function has to be called from a platform specific context, the corresponding std type can be used as the passed in argument type (i.e. use std::wstring on Windows):

    std::wstring searchText = L"Michael";
    MyTest(searchText);