2014-11-05 124 views
6

我需要編寫一個命令行客戶端來在服務器上播放井字遊戲。 服務器接受http請求並將json發送回我的客戶端。我正在尋找一種快速的方式來發送一個http請求,並使用boost庫接收json作爲字符串。如何發送http請求並檢索json響應C++ Boost

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

注意的嚴重的企業(主要是現有的Web服務器分塊編碼,壓縮,保持活動,重定向響應等),你會想要使用庫http://curl.haxx.se/libcurl/ – sehe 2014-11-05 16:33:19

回答

8

適合描述最簡單的事情:

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(雖然他們專注於異步通信,因爲這是短耳庫的主題),可能做的任何方式

+0

非常感謝答覆:)但我有點麻煩, – 2014-11-07 11:26:24

+0

非常感謝回覆:)但我遇到了一些問題,使用以下代碼:'code'sock.connect({{},8087})'code'和:'code'size_t bytes_transferred = sock.receive(buffer (buf),{},ec)'code'我應該把什麼放在大括號裏面。我做了一個小的閱讀,第二個我試圖做一個空的socket_base :: message_flags標誌;並通過它,但我的程序似乎崩潰。 – 2014-11-07 11:37:01

+0

這是一個'{{},8087}'是'ip :: tcp :: endpoint(ip :: address(),8087)'的縮寫。你放什麼取決於你(你想連接到什麼?)。通常,最終用戶將地址和端口指定爲字符串,並使用** ['ip :: tcp :: resolver'](http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/reference /ip__tcp/resolver.html)**解析爲端點。幾乎所有的客戶樣品都會告訴你如何做到這一點((a)同步)。或者,可使用ip :: address_v4 :: from_string(「192.168.0.1」)來硬編碼ipv4地址,例如, – sehe 2014-11-07 11:42:00

相關問題