如何发送 http 请求并检索 json 响应 C++ Boost
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26761058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send http request and retrieve a json response C++ Boost
提问by Mladen Kajic
I need to write a command line client for playing tic-tac-toe over a server. the server accepts http requests and sends back json to my client. i am looking for a quick way to send a http request and receive the json as a string using boost libraries.
我需要编写一个命令行客户端来在服务器上玩井字游戏。服务器接受 http 请求并将 json 发送回我的客户端。我正在寻找一种快速方法来发送 http 请求并使用 boost 库将 json 作为字符串接收。
example http request = "http://???/newGame?name=david"
example json response = "\"status\":\"okay\", \"id\":\"game-23\", \"letter\":2"
回答by sehe
The simplest thing that fits the description:
符合描述的最简单的事情:
#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";
}
This receives the full response. You can test it with a dummy server:
(also Live On Coliru):
这将收到完整的响应。您可以使用虚拟服务器对其进行测试:(
也Live On Coliru):
netcat -l localhost 8087 <<< '"status":"okay", "id":"game-23", "letter":2'
This will show that the request is received, and the response will be written out by our client code above.
这将表明收到了请求,并且响应将由我们上面的客户端代码写出。
Note that for more ideas you could look at the examples http://www.boost.org/doc/libs/release/doc/html/boost_asio/examples.html(although they focus on asynchronous communications, because that's the topic of the Asio library)
请注意,有关更多想法,您可以查看示例http://www.boost.org/doc/libs/release/doc/html/boost_asio/examples.html(尽管它们专注于异步通信,因为这是Asio图书馆)