Files
baidu_fanyi/bf.request.cpp
2026-03-10 14:32:11 +08:00

120 lines
3.6 KiB
C++

#include "bf.request.h"
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#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<int>(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<char*>(buffer), totalSize);
return totalSize;
}
bool BF_Request::HandleStr(const std::string& jsonMsg, std::string& out)
{
out.clear();
if (jsonMsg.empty()) {
gLogger->error("JSON消息为空");
return false;
}
try {
nlohmann::json j = nlohmann::json::parse(jsonMsg);
if (j.contains("error_code")) {
std::string errorCode = j["error_code"];
std::string errorMsg = j.value("error_msg", "未知错误");
gLogger->error("翻译API返回错误: code={}, msg={}", errorCode, errorMsg);
return false;
}
if (!j.contains("trans_result")) {
gLogger->error("JSON中缺少trans_result字段");
return false;
}
const auto& transResult = j["trans_result"];
if (!transResult.is_array() || transResult.empty()) {
gLogger->error("trans_result不是有效数组或为空");
return false;
}
std::vector<std::string> translations;
for (const auto& item : transResult) {
if (item.contains("dst")) {
translations.push_back(item["dst"].get<std::string>());
}
}
if (translations.empty()) {
gLogger->error("未找到有效的翻译结果");
return false;
}
for (size_t i = 0; i < translations.size(); ++i) {
out += translations[i];
if (i < translations.size() - 1) {
out += "\n";
}
}
return true;
} catch (const nlohmann::json::exception& e) {
gLogger->error("JSON解析失败: {}, 原始数据: {}", e.what(), jsonMsg);
return false;
} catch (const std::exception& e) {
gLogger->error("处理JSON时发生异常: {}, 原始数据: {}", e.what(), jsonMsg);
return false;
}
}