diff --git a/include/opendht/http.h b/include/opendht/http.h index d43e78cb626864e0990239811e01847a4122f410..380802264440fa12eb5cdc5de34bd575c7ea8424 100644 --- a/include/opendht/http.h +++ b/include/opendht/http.h @@ -212,6 +212,7 @@ public: using OnDataCb = std::function<void(const char* at, size_t length)>; using OnStateChangeCb = std::function<void(State state, const Response& response)>; using OnJsonCb = std::function<void(Json::Value value, unsigned int status_code)>; + using OnDoneCb = std::function<void(const Response& response)>; // resolves implicitly Request(asio::io_context& ctx, const std::string& url, const Json::Value& json, OnJsonCb jsoncb, @@ -219,6 +220,7 @@ public: Request(asio::io_context& ctx, const std::string& url, std::shared_ptr<dht::Logger> logger = {}); Request(asio::io_context& ctx, const std::string& host, const std::string& service, const bool ssl = false, std::shared_ptr<dht::Logger> logger = {}); + Request(asio::io_context& ctx, const std::string& url, OnDoneCb onDone, std::shared_ptr<dht::Logger> logger = {}); // user defined resolver Request(asio::io_context& ctx, std::shared_ptr<Resolver> resolver, sa_family_t family = AF_UNSPEC); diff --git a/src/http.cpp b/src/http.cpp index abb9611be24fefb837e767852af1f63dbce28762..d34da523813d1bd0b79e72d22653052948de2a70 100644 --- a/src/http.cpp +++ b/src/http.cpp @@ -443,11 +443,13 @@ Request::Request(asio::io_context& ctx, const std::string& url, const Json::Valu if (state != Request::State::DONE) return; Json::Value json; - std::string err; - Json::CharReaderBuilder rbuilder; - auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); - if (!reader->parse(response.body.data(), response.body.data() + response.body.size(), &json, &err) and logger_) - logger_->e("[http:request:%i] can't parse response to json", id_, err.c_str()); + if (response.status_code != 0) { + std::string err; + Json::CharReaderBuilder rbuilder; + auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); + if (!reader->parse(response.body.data(), response.body.data() + response.body.size(), &json, &err) and logger_) + logger_->e("[http:request:%i] can't parse response to json", id_, err.c_str()); + } if (jsoncb) jsoncb(json, response.status_code); }); @@ -460,6 +462,15 @@ Request::Request(asio::io_context& ctx, const std::string& url, std::shared_ptr< init_default_headers(); } +Request::Request(asio::io_context& ctx, const std::string& url, OnDoneCb onDone, std::shared_ptr<dht::Logger> logger) + : logger_(logger), id_(Request::ids_++), ctx_(ctx), resolver_(std::make_shared<Resolver>(ctx, url, logger)) +{ + add_on_state_change_callback([this, onDone](State state, const Response& response){ + if (state == Request::State::DONE) + onDone(response); + }); +} + Request::Request(asio::io_context& ctx, const std::string& host, const std::string& service, const bool ssl, std::shared_ptr<dht::Logger> logger) : logger_(logger), id_(Request::ids_++), ctx_(ctx),