Websocketpp简单的HTTP客户端

nok*_*ome 2 c++ websocket websocket++

我使用优秀的websocketpp库在C++应用程序中提供Websockets(和HTTP)服务器.我还需要在同一个应用程序中的HTTP客户端连接到REST API.我也一直在websocketpp尝试这个,但到目前为止我没有成功.以下初步尝试为我提供了这个日志输出:

[2015-03-06 18:01:18] [connect] Successful connection
[2015-03-06 18:01:18] [error] Server handshake response error: websocketpp.processor:20 (Invalid HTTP status.)
[2015-03-06 18:01:18] [disconnect] Failed: Invalid HTTP status.
Run Code Online (Sandbox Code Playgroud)

这表明我的http_处理程序方法可能需要更多.任何意见,将不胜感激.websocketpp文档和示例似乎不包含简单的HTTP客户端.

#define _WEBSOCKETPP_CPP11_STL_
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/common/thread.hpp>

namespace {

using namespace websocketpp;
typedef client<websocketpp::config::asio_client> client;

class Client {
public:

    Client(void){
        client_.init_asio();
        client_.set_http_handler(bind(&Client::http_,this,_1));
    }

    std::string get(const std::string& url) {
        websocketpp::lib::error_code error;
        client::connection_ptr con = client_.get_connection(url,error);
        if(error) std::runtime_error("Unable to connnect.\n  url: "+url+"\n  message: "+error.message());
        client_.connect(con);
        websocketpp::lib::thread asio_thread(&client::run, &client_);
        asio_thread.join();
        return data_;
    }

private:

    void http_(connection_hdl hdl){
        std::cout<<"Connected\n";
        data_ = "http payload";
    }

    client client_;
    std::string data_;
};

}

int main(void){
    Client client;
    client.get("http://google.com/");
}
Run Code Online (Sandbox Code Playgroud)

zap*_*oyd 6

WebSocket ++的HTTP处理功能是一种便利功能,旨在允许WebSocket服务器以有限的容量提供HTTP响应.WebSocket ++不适合用作通用HTTP库,也不包含扮演(非WebSocket)HTTP客户端角色的能力.

对HTTP客户端功能使用单独的库(例如cpp-netlib)是一个很好的解决方案.