多用一个库,多一个坑,用一个库就要用足它的红利,可能的情况下尽量采纳同一个库。前面采用来restbed 来实现websocket 和http server ,今天需要写一个influxdb 的C++客户端。有一次选用restbed 来作为 http客户端。网上建议比较多的是微软的 C++ REST SDK (https://github.com/Microsoft/cpprestsdk),我还是使用老伙计restbed。
#include <memory>
#include <future>
#include <cstdio>
#include <cstdlib>
#include <restbed>
#include <string>
#include <iostream>
using namespace std;
using namespace restbed;
int main( const int, const char** )
{
string messsgae_body="{\"hello\":\"yao\"}";
auto request = make_shared< Request >( Uri( "http://localhost:8000/hello" ) );
request->add_header("Content-Type","application/json");
request->add_header("Content-Length",to_string(messsgae_body.length()));
request->set_body(messsgae_body);
auto response = Http::sync( request );
auto length = response->get_header( "Content-Length", 0 );
Http::fetch( length, response );
string response_body((char*) response->get_body().data());
cout<<"response:"<<response_body<<endl;
return EXIT_SUCCESS;
}
很简单吧?