gpt4 book ai didi

C++ REST SDK a.k.a 卡萨布兰卡

转载 作者:行者123 更新时间:2023-11-30 05:02:41 26 4
gpt4 key购买 nike

如何使用 c++ rest sdk aka casablanca 从 api 返回 coutprintf 数据?

我从教程中得到了这段代码:

#include "stdafx.h"

#include <cpprest/http_client.h>
#include <cpprest/filestream.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

int main(int argc, char* argv[])
{
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("http://192.168.0.13:3000/api/individual_employment_setting/detail/172"));

// Build request URI and start the request.
//uri_builder builder(U("/search"));
//builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET);
})

// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());

// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})

// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});

// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}

return 0;
}

但它只是将一个文件写入一个 .html 文件。

有没有办法将api的返回数据存储到一个变量中,然后像cout或printf一样在终端输出?谢谢。

最佳答案

您可以尝试使用字符串流缓冲区而不是您现在正在使用的文件流缓冲区来读取响应主体:

    // Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());

stringstreambuf buffer;
response.body().read_to_end(buffer).get();

//show content in console
printf("Response body: \n %s", buffer.collection().c_str());

//parse content into a JSON object:
json::value jsonvalue = json::value::parse(buffer.collection());

//write content to file
return fileStream->print(buffer.collection());
})

关于C++ REST SDK a.k.a 卡萨布兰卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49748228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com