c++ rest websocket的使用方式

1. rest使用方式

(1)GET

 http_client restclient("https://test.123456.com");   // base url  
 http_request request(methods::GET);
        
 request.headers().add("TestKey", "TestValue");
 request.headers().add("Content-Type", "application/json");
       
 uri_builder builder("/api/test/get_something");   // 是base url后边的地址
   builder.append_query("price", 100);
   char temp[24];
   sprintf(temp, "%.8f", 20);
   builder.append_query("amount", temp);
   builder.append_query("label", "123456");
   builder.append_query("name", "test");
   builder.append_query("type", "new");
 request.set_request_uri(builder.to_string()); // builder.to_string() = /api/test/get_something?price=100.0000&amount=20.00000000&label=123456&name=123456&type=new

 restclient.request(request).then([](http_response response) -> pplx::task<json::value> {
     // if the status is OK extract the body of the response into a JSON value works only when the content type is application\json
     auto code = response.status_code();//400, 401, 418, 429
     if(code == status_codes::OK || code == status_codes::BadRequest || code == status_codes::TooManyRequests || code == status_codes::Unauthorized) 
     {
         return response.extract_json();
     }
      throw exception();
      return pplx::task_from_result(json::value());  // return an empty JSON value
}).then([&](pplx::task<json::value> previousTask) { // get the JSON value from the task and display content from it 
try {
json::value const & v = previousTask.get();
} catch (http_exception const & e) {
     throw exception();
}
}) .wait();

(2) POST 

 http_client restclient("https://test.123456.com"); 
http_request request(methods::PUT); request.headers().add(
"TestKey", "TestValue"); request.headers().add("Content-Type", "application/json"); uri_builder builder("api/test/put_something"); request.set_request_uri(builder.to_string());

json::value body; body["price"] = json::value::number(100); body["amount"] = json::value::amount(10); body["label"] = json::value::string("123456"); body["name"] = json::value::number("test"); body["type"] = json::value::number("new"); request.set_body(body.serialize()); // body.to_string() = {"price":100,"amount":10,"label":"123456","name":"test","type":"new"} restclient.request(request).then([](http_response response) -> pplx::task<json::value> { // if the status is OK extract the body of the response into a JSON value works only when the content type is application\json auto code = response.status_code(); //400, 401, 418, 429 if(code == status_codes::OK || code == status_codes::BadRequest || code == status_codes::TooManyRequests || code == status_codes::Unauthorized) { return response.extract_json(); } throw exception(); // return an empty JSON value return pplx::task_from_result(json::value()); }).then([&](pplx::task<json::value> previousTask) { // get the JSON value from the task and display content from it try { json::value const & v = previousTask.get(); } catch (http_exception const & e) { throw exception(); } }).wait();

 

2. websocket连接,接收,订阅
    uri_builder builder("wss://test.123456.com");
    builder.append_path("/ws/api/test");
      websocket_callback_client  m_wsclient;
    m_wsclient.close();
    m_wsclient.connect(builder.to_string())
    .then([&]() { 
        std::function<void (const websocket_incoming_message &msg)> f;
        f = std::bind(&TestClass::On_WebSocketMsg, this, placeholders::_1);
        m_wsclient.set_message_handler(f);
        std::function<void (websocket_close_status close_status,
                                const utility::string_t& reason,
                                const std::error_code& error)> c;
        c =  std::bind(&TestClass::On_CloseMsg, this, placeholders::_1, placeholders::_2, placeholders::_3);
        m_wsclient.set_close_handler(c);
    })
    .wait();

class TestClass {
  public:
    void On_WebSocketMsg(const websocket_incoming_message& msg) {
    auto type = (int)msg.message_type();
       if (type == 2 || type == 3) {
      // send ping
    } else if (type == 0) {
      msg.extract_string().then([](const string s) {
        web::json::value res = json::value::parse(s.c_str());
        if (res.has_field("result")) {
        }
      })
    }
  }

    void On_CloseMsg(websocket_close_status close_status, const utility::string_t& reason, const std::error_code& error) {
    }
 
  void Ping() {
    websocket_outgoing_message out_msg;
    out_msg.set_ping_message();
    m_wsclient.send(out_msg);
  }
 
  void Pong() {
    websocket_outgoing_message out_msg;
    out_msg.set_pong_message();
    m_wsclient.send(out_msg);
  }
 
  void Subscribe() {
     websocket_outgoing_message out_msg;
      json::value msg;
      //msg["method"] = json::value::string("public/subscribe");
      msg["method"] = json::value::string("private/subscribe");
      //json::value channel = json::value::string("ticker.BTC-11MAR22-30000-C.100ms");
      json::value channel = json::value::string("user.orders.BTC-PERPETUAL.100ms");
      vector<json::value> v;
      v.push_back(channel);

      json::value params;
      params["channels"] = json::value::array(v);
      params["access_token"] = json::value::string("access_token");  // 添加认证方式(如果需要的话)
      msg["params"] = params;
      std::cout << msg.to_string() << std::endl;
 
      out_msg.set_utf8_message(msg.serialize());
      m_wsclient.send(out_msg);
  }
};

 

posted @ 2022-03-10 11:43  c++11  阅读(448)  评论(0编辑  收藏  举报