c++ - 从 CPPRest 库(即 casablanca)获得的结果中提取基本 STL 字符串?

标签 c++ rest stl iostream

我正在努力学习两件事: 1) 一些基本的 C++ STL(我是一个老 C/C++ 程序员,正在尝试学习新东西) 2) 如何使用 CPPRest library 通过 REST 服务访问我的奇妙 list 帐户.

我已经能够使用奇妙 list 成功启动 oauth2 进程,但为了帮助我了解正在发生的事情和返回的内容,我只想打印结果字符串。对于我的一生,我不知道该怎么做。它与操作 iostreams 有关,但由于我是新手,所以我很挣扎。

这是一个代码片段,它成功地将 HTML 从最初的 Wunderlist 响应获取到一个 streambuf,但我无法将它变成一个字符串以供打印(或其他)。请注意,我不关心异步执行此操作;因此,我只是通过 !task.is_done() 强制同步。另外,如果你想编译和运行你需要为 Wunderlist 提供你自己的 client_id,或者使用不同的服务。

#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;
}

最佳答案

有一种独立于平台的方法可以从 http_response 对象中提取字符串:

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

关于c++ - 从 CPPRest 库(即 casablanca)获得的结果中提取基本 STL 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560337/

相关文章:

java - 使用 Apache HttpClient 和负载平衡的 SharePoint REST 调用在首次 GET 后失败

c++ - 不应该像这样从 STL::list 中删除进入无限循环吗?

c++ - 重载 I/O 流运算符和前/后递增/递减运算符错误?

c++ - 在 C++11 中,如何不向线程传递参数?

rest - 认证2 : how should the resource server know if the access token is valid?

rest - 不同的资源表示(REST API)

c++ - 在 STL 中使用 void* 作为固定宽度的记录

c++ - 简单的 C++ hash_set 示例

.net - 如何将 GetType() 用于 CheckBox?

c++ - 正则表达式从 netsh wlan 获取 MAC 地址