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

C++ REST SDK a.k.a Casablanka

如何使用 c++ rest sdk aka casablanca?

coutprintf 来自 api 的数据 return

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

#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 的 return 数据存储到一个变量中,然后像 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());
})