1

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

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

#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 等终端中输出?谢谢。

4

1 回答 1

1

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

    // 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());
})
于 2018-04-10T09:00:24.447 回答