diff --git a/src/Http/HttpRequester.cpp b/src/Http/HttpRequester.cpp index e6e91378..669d17fe 100644 --- a/src/Http/HttpRequester.cpp +++ b/src/Http/HttpRequester.cpp @@ -11,7 +11,7 @@ #include "HttpRequester.h" #include "Util/onceToken.h" #include "Util/NoticeCenter.h" - +#include using namespace std; using namespace toolkit; @@ -26,6 +26,17 @@ void HttpRequester::onResponseBody(const char *buf, size_t size) { } void HttpRequester::onResponseCompleted(const SockException &ex) { + if (ex && _retry++ < _max_retry) { + std::weak_ptr weak_self = std::dynamic_pointer_cast(shared_from_this()); + getPoller()->doDelayTask(_retry_delay, [weak_self](){ + if (auto self = weak_self.lock()) { + InfoL << "resend request " << self->getUrl() << " with retry " << self->getRetry(); + self->sendRequest(self->getUrl()); + } + return 0; + }); + return ; + } const_cast(response()).setContent(std::move(_res_body)); if (_on_result) { _on_result(ex, response()); @@ -33,8 +44,15 @@ void HttpRequester::onResponseCompleted(const SockException &ex) { } } +void HttpRequester::setRetry(size_t count, size_t delay) { + InfoL << "setRetry max=" << count << ", delay=" << delay; + _max_retry = count; + _retry_delay = delay; +} + void HttpRequester::startRequester(const string &url, const HttpRequesterResult &on_result, float timeout_sec) { _on_result = on_result; + _retry = 0; setCompleteTimeout(timeout_sec * 1000); sendRequest(url); } diff --git a/src/Http/HttpRequester.h b/src/Http/HttpRequester.h index 69dd05a6..067bb0e8 100644 --- a/src/Http/HttpRequester.h +++ b/src/Http/HttpRequester.h @@ -25,6 +25,10 @@ public: void setOnResult(const HttpRequesterResult &onResult); void startRequester(const std::string &url, const HttpRequesterResult &on_result, float timeout_sec = 10); + void setRetry(size_t count, size_t delay); + size_t getRetry() const { return _retry; } + size_t getRetryDelay() const { return _retry_delay; } + size_t getMaxRetry() const { return _max_retry; } void clear() override; private: @@ -33,6 +37,9 @@ private: void onResponseCompleted(const toolkit::SockException &ex) override; private: + size_t _retry = 0; + size_t _max_retry = 0; + size_t _retry_delay = 2000; // ms std::string _res_body; HttpRequesterResult _on_result; };