c++ - 如何发送 http 请求并检索 json 响应 C++ Boost

标签 c++ json http boost

我需要编写一个命令行客户端来在服务器上玩井字游戏。 服务器接受 http 请求并将 json 发送回我的客户端。我正在寻找一种使用 boost 库发送 http 请求并以字符串形式接收 json 的快速方法。

example http request = "http://???/newGame?name=david"
example json response = "\"status\":\"okay\", \"id\":\"game-23\", \"letter\":2"

最佳答案

符合描述的最简单的事情:

Live On Coliru

#include <boost/asio.hpp>
#include <iostream>

int main() {
    boost::system::error_code ec;
    using namespace boost::asio;

    // what we need
    io_service svc;
    ip::tcp::socket sock(svc);
    sock.connect({ {}, 8087 }); // http://localhost:8087 for testing

    // send request
    std::string request("GET /newGame?name=david HTTP/1.1\r\n\r\n");
    sock.send(buffer(request));

    // read response
    std::string response;

    do {
        char buf[1024];
        size_t bytes_transferred = sock.receive(buffer(buf), {}, ec);
        if (!ec) response.append(buf, buf + bytes_transferred);
    } while (!ec);

    // print and exit
    std::cout << "Response received: '" << response << "'\n";
}

这会收到完整的回复。您可以使用虚拟服务器对其进行测试:
(也为 Live On Coliru ):

netcat -l localhost 8087 <<< '"status":"okay", "id":"game-23", "letter":2'

这将显示请求已收到,响应将由我们上面的客户端代码写出。

请注意,有关更多想法,您可以查看示例 http://www.boost.org/doc/libs/release/doc/html/boost_asio/examples.html (尽管他们专注于异步通信,因为那是 Asio 库的主题)

关于c++ - 如何发送 http 请求并检索 json 响应 C++ Boost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26761058/

相关文章:

c# - 在 Azure 函数中读取包含 pdf 的请求正文时出错

C++,如何在非并行任务中通过线程准确划分cpu工作

c++ - Boost单元测试计时机制

javascript - "reset"对象的属性顺序如何? JSON.stringify() 保留它们

http - 在 HTTP 502 中,无效响应是什么意思?

ruby - 用完 Net::HTTP 的套接字连接

c++ - 运算符 [] 错误无效类型 'Config*[const char [8]]' 用于数组下标

c++ - 什么样的 .lib 文件以 "!<arch>"开头?

javascript - D3可以读取 "Geojson"文件吗?

python - Pandas 按多列分组时组合键