我需要编写一个命令行客户端来在服务器上玩井字游戏。 服务器接受 http 请求并将 json 发送回我的客户端。我正在寻找一种使用 boost 库发送 http 请求并以字符串形式接收 json 的快速方法。
example http request = "http://???/newGame?name=david"
example json response = "\"status\":\"okay\", \"id\":\"game-23\", \"letter\":2"
最佳答案
符合描述的最简单的事情:
#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/