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

时间:2014-11-05 15:37:32

标签: c++ json http boost

我需要编写一个命令行客户端,用于在服务器上播放tic-tac-toe。 服务器接受http请求并将json发送回我的客户端。我正在寻找一种快速方式来发送http请求并使用boost库接收json作为字符串。

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

1 个答案:

答案 0 :(得分:9)

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

<强> 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库的主题)