使用C ++ REST SDK将Stream响应转换为byte []

时间:2016-12-21 13:48:57

标签: c++ rest

我正在使用C ++ REST SDK从API获取响应,我需要将Concurrency::streams::basic_istream转换为byte[]

pplx::task<void> GetResponse()
{
    http_client client(url);
    return client.request(methods::GET).then([](http_response response)
    {
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
        std::wcout << ss.str();

        auto bodyStream = response.body();
    });
}

bodyStream的类型为Concurrency::streams::basic_istream

我得到的回复content-typeapplication/octet-stream

如何将其转换为byte[]

1 个答案:

答案 0 :(得分:0)

如何使用http_response::extract_vector方法将响应主体作为字节数组返回?

pplx::task<std::vector<unsigned char>> GetResponse()
{
    http_client client(url);
    return client.request(methods::GET).then([](http_response response)
    {
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
        std::wcout << ss.str();

        return response.extract_vector();
    });
}

如果您不需要stdout日志记录,甚至更简单:

pplx::task<std::vector<unsigned char>> GetResponse()
{
    http_client client(url);
    return client.request(methods::GET).get().extract_vector();
}

然后,您可以在返回的data()上调用vector以获取指向底层unsigned char数组的指针(相当于一个字节数组)。