【问题标题】:cpprestsdk: handle chunked responsecpprestsdk:处理分块响应
【发布时间】:2017-03-21 09:32:44
【问题描述】:

我应该如何使用 cpprestsdk 处理分块响应?如何请求下一个块?那里有必要的功能吗?

以下是我们执行 http 请求的方式:

web::http::http_request request(web::http::methods::GET);
request.headers().add(LR"(User-Agent)", LR"(ExchangeServicesClient/15.00.0847.030)");
request.headers().add(LR"(Accept)", LR"(text/xml)");
request.set_body(L"request body", L"text/xml");

web::http::client::http_client_config clientConfig;
clientConfig.set_credentials(web::credentials(L"username", L"pass"));
clientConfig.set_validate_certificates(true);

web::http::client::http_client client(L"serviceurl", clientConfig);

auto bodyTask = client.request(request)
    .then([](web::http::http_response response) {
        auto str = response.extract_string().get();
        return str;
});

auto body = bodyTask.get();

如果我在这个请求之后天真地尝试执行另一个请求,那么我得到一个错误:

WinHttpSendRequest: 5023: 组或资源未处于正确的状态以执行 请求的操作。

【问题讨论】:

标签: c++ chunked-encoding casablanca cpprest-sdk


【解决方案1】:

为了分块读取接收到的数据,需要从服务器响应中获取输入流

concurrency::streams::istream bodyStream = response.body();

然后从该流中连续读取,直到找到给定的字符或读取指定的字节数

pplx::task<void> repeat(Concurrency::streams::istream bodyStream)
{
Concurrency::streams::container_buffer<std::string> buffer;

return pplx::create_task([=] {
    auto t = bodyStream.read_to_delim(buffer, '\n').get();
    std::cout << buffer.collection() << std::endl;
    return t;
}).then([=](int /*bytesRead*/) {
    if (bodyStream.is_eof()) {
        return pplx::create_task([]{});
    }
    return repeat(bodyStream);
});
}

这里是完整示例:https://github.com/cristeab/oanda_stream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 2012-10-21
    • 2014-11-27
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    相关资源
    最近更新 更多