#include "bf.request.h" #include #include "bf.util.h" BF_Request::BF_Request() { curl_global_init(CURL_GLOBAL_DEFAULT); curl_ = curl_easy_init(); } BF_Request::~BF_Request() { curl_easy_cleanup(curl_); curl_global_cleanup(); } std::string BF_Request::getResult(const std::string& url) { std::string reponse; if (!curl_) { gLogger->error("curl init failed."); return reponse; } curl_easy_setopt(curl_, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl_, CURLOPT_POST, 0L); curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, writeData); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &reponse); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L); CURLcode res = curl_easy_perform(curl_); if (res != CURLE_OK) { gLogger->error("curl request failed. error code: {}", static_cast(res)); return reponse; } return reponse; } std::string BF_Request::doReady(const std::string& words, const std::string& from, const std::string& to) { char* buffer = new char[2048]{}; auto rs = BF_Util::RandomStrNum(); auto s = fmt::format("{}{}{}{}", config_->appId, words, rs, config_->appSecret); auto md5 = BF_Util::MD5(s); auto reqWords = BF_Util::urlEncode(words); std::snprintf(buffer, 2048, "q=%s&from=%s&to=%s&appid=%s&salt=%s&sign=%s", reqWords.c_str(), from.c_str(), to.c_str(), config_->appId.c_str(), rs.c_str(), md5.c_str()); std::string data(buffer); delete[] buffer; return data; } size_t BF_Request::writeData(void* buffer, size_t size, size_t nmemb, std::string* str) { auto totalSize = size * nmemb; str->append(static_cast(buffer), totalSize); return totalSize; }