Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send http request and retrieve a json response C++ Boost

Tags:

c++

json

http

boost

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.

example http request = "http://???/newGame?name=david"
example json response = "\"status\":\"okay\", \"id\":\"game-23\", \"letter\":2"
like image 374
Mladen Kajic Avatar asked Nov 05 '14 15:11

Mladen Kajic


People also ask

How do I get HTTP response as JSON?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

Can I send JSON data in GET request?

To get JSON from a REST API endpoint, you must send an HTTP GET request and pass the "Accept: application/json" request header to the server, which will tell the server that the client expects JSON in response.


1 Answers

The simplest thing that fits the description:

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

This receives the full response. You can test it with a dummy server:
(also 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)

like image 105
sehe Avatar answered Sep 30 '22 10:09

sehe