How to send an HTTP request and get json C ++ Boost response

I need to write a command line client to play tic-tac-toe on the server. the server accepts HTTP requests and sends json back to my client. I am looking for a quick way to send an HTTP request and get json as a string using boost libraries.

example http request = "http://???/newGame?name=david" example json response = "\"status\":\"okay\", \"id\":\"game-23\", \"letter\":2" 
+6
source share
1 answer

The simplest thing to describe:

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"; } 

Gets the full response. You can test it using a dummy server:
(also Live On Coliru ) :

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

This will show that the request has been received and the response will be written out by our client above.

Note that for more ideas, you can see examples http://www.boost.org/doc/libs/release/doc/html/boost_asio/examples.html (although they focus on asynchronous messages because the topic is Asio)

+8
source

Source: https://habr.com/ru/post/977772/


All Articles