提问人:Jim Griesmer 提问时间:1/2/2016 更新时间:1/2/2016 访问量:932
从 CPPRest 库(即卡萨布兰卡)获得的结果中提取基本的 STL 字符串?
Basic STL string extraction from results obtained from CPPRest libraries (i.e. casablanca)?
问:
我正在尝试学习两件事: 1)一些基本的C++ STL(我是一个老C/C++编码员,试图学习新东西) 2)如何使用CPPRest库通过REST服务访问我的wunderlist帐户。
我已经能够使用 Wunderlist 成功启动 oauth2 进程,但为了帮助我了解正在发生的事情和返回的内容,我想做的就是打印结果字符串。对于我的生活,我不知道该怎么做。它与操纵 iostream 有关,但由于我是这些新手,所以我很挣扎。
这是一个代码片段,它成功地将 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;
}
答:
2赞
huu
1/2/2016
#1
有一种独立于平台的方法可以从对象中提取字符串: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
评论
0赞
Jim Griesmer
1/2/2016
啊,做到了。谢谢huu。我现在可以取得进步了。但是,我仍然觉得通过 body() 函数获取响应正文,然后将其读入 streambuf 在某种程度上是有意义的。我的意思是填充一个 streambuf<char> 对象有什么好处,我可以用数据填充它,但我不能以任何方式、形状或形式读回?也许我只需要花更多的时间研究流......叹息。。。
0赞
huu
1/2/2016
有些任务用流更自然地表示,例如,写入文件。如果您只是想将响应字符串作为普通的旧字符串对象获取,那么您根本不需要弄乱流缓冲区。如果省略有关输出流或流缓冲区的所有行,则上述示例可以正常工作。
0赞
Jim Griesmer
1/3/2016
明白了。我基本上是从另一个将结果数据输出到文件的样本中复制的......因此,它使用了文件流。由于我不想打开文件来查看结果,所以我想我只需要进行从文件流到字符串流的转换,但正如您指出的那样,这使其过于复杂。再次感谢。
评论