改用Poco请求。

This commit is contained in:
2026-03-24 10:28:37 +08:00
parent d3bfc82299
commit 927c9c19bf
7 changed files with 122 additions and 43 deletions

12
.vscode/settings.json vendored
View File

@@ -34,10 +34,14 @@
"cmake.configureArgs": [
"-Wno-dev"
],
// "cmake.configureSettings": {
// "CMAKE_TOOLCHAIN_FILE": "${env:VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
// },
"cmake.configureSettings": {
//"CMAKE_TOOLCHAIN_FILE": "${env:VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
"CMAKE_PREFIX_PATH": [
"C:\\local",
"D:\\program\\mingw64\\opt"
],
"OPENSSL_ROOT_DIR": "D:\\program\\mingw64\\opt"
},
"cmake.options.statusBarVisibility": "visible",
"cmake.generator": "Ninja",
"C_Cpp.default.compileCommands": "${workspaceRoot}/build/compile_commands.json",

View File

@@ -14,16 +14,19 @@ if (MSVC)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif()
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib/)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin/)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE})
find_package(CURL CONFIG REQUIRED)
find_package(OpenSSL CONFIG REQUIRED)
find_package(cxxLibrary CONFIG REQUIRED)
find_package(Xlnt CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)
find_package(CLI11 CONFIG REQUIRED)
find_package(spdlog CONFIG REQUIRED)
find_package(fmt CONFIG REQUIRED)
find_package(OpenSSL CONFIG REQUIRED)
find_package(Poco REQUIRED COMPONENTS
Foundation
Net
Util
JSON
NetSSL
)
set(SOURCES
bf.config.cpp bf.config.h
@@ -36,11 +39,21 @@ bf.xlnt.cpp bf.xlnt.h
add_executable(baidu_fanyi main.cpp ${SOURCES})
add_executable(cli_test cli_test.cpp)
target_link_libraries(baidu_fanyi PRIVATE
xlnt::xlnt OpenSSL::SSL OpenSSL::Crypto
CURL::libcurl nlohmann_json::nlohmann_json
CLI11::CLI11 spdlog::spdlog fmt::fmt
xlnt::xlnt
OpenSSL::SSL
OpenSSL::Crypto
cxxLibrary::cxxLibrary
Poco::Foundation
Poco::Net
Poco::Util
Poco::JSON
Poco::NetSSL
)
target_link_libraries(cli_test PRIVATE CLI11::CLI11)
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_SYSTEM_NAME MATCHES "Windows")
# mingw64 编译的 xlnt 需要这个。
target_link_libraries(baidu_fanyi PRIVATE gcov)
endif()
target_link_libraries(cli_test PRIVATE cxxLibrary::cxxLibrary)
execute_process(
COMMAND ${CMAKE_COMMAND} -E copy_if_different

View File

@@ -1,43 +1,94 @@
#include "bf.request.h"
// Poco 头文件
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
// SSL 相关头文件
#include <Poco/Net/AcceptCertificateHandler.h>
#include <Poco/Net/Context.h>
#include <Poco/Net/InvalidCertificateHandler.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/SharedPtr.h>
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <sstream>
#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;
std::string response;
try {
Poco::URI uri(url);
// 禁用SSL验证(模拟curl的SSL_VERIFYHOST=0, SSL_VERIFYPEER=0)
Poco::Net::initializeSSL();
Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> pCertHandler = new Poco::Net::AcceptCertificateHandler(false);
Poco::Net::Context::Ptr pContext =
new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE, 9, true);
Poco::Net::SSLManager::instance().initializeClient(0, pCertHandler, pContext);
std::unique_ptr<Poco::Net::HTTPClientSession> pSession;
if (uri.getScheme() == "https") {
// HTTPS
pSession = std::make_unique<Poco::Net::HTTPSClientSession>(uri.getHost(), uri.getPort(), pContext);
} else {
// HTTP
pSession = std::make_unique<Poco::Net::HTTPClientSession>(uri.getHost(), uri.getPort());
}
std::string path(uri.getPathAndQuery());
if (path.empty())
path = "/";
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
// 添加必要的请求头
request.set("User-Agent", "Mozilla/5.0 (compatible; baidu_fanyi/1.0)");
request.set("Accept", "*/*");
request.set("Connection", "close");
pSession->setTimeout(Poco::Timespan(10, 0)); // 10秒超时
pSession->sendRequest(request);
Poco::Net::HTTPResponse httpResponse;
std::istream& rs = pSession->receiveResponse(httpResponse);
if (httpResponse.getStatus() != Poco::Net::HTTPResponse::HTTP_OK) {
gLogger->error("HTTP request failed. Status: {} - {}", static_cast<int>(httpResponse.getStatus()),
httpResponse.getReason());
return response;
}
std::stringstream ss;
Poco::StreamCopier::copyStream(rs, ss);
response = ss.str();
} catch (const Poco::Exception& e) {
gLogger->error("Poco request failed. Error: {}", e.displayText());
} catch (const std::exception& e) {
gLogger->error("Request failed. Error: {}", e.what());
}
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);
Poco::Net::uninitializeSSL(); // 清理SSL
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;
return response;
}
std::string BF_Request::doReady(const std::string& words, const std::string& from, const std::string& to)

View File

@@ -1,8 +1,6 @@
#ifndef BF_REQUEST_H
#define BF_REQUEST_H
#include <curl/curl.h>
#include "bf.interface.h"
#include "bf.util.h"
#include "bf.config.h"
@@ -22,9 +20,6 @@ public:
private:
static size_t writeData(void* buffer, size_t size, size_t nmemb, std::string* str);
private:
CURL* curl_{};
};
#endif

View File

@@ -1,4 +1,4 @@
#include <CLI/CLI.hpp>
#include <CLI11.hpp>
#include <iostream>
#ifdef _WIN32

View File

@@ -1,4 +1,4 @@
#include <CLI/CLI.hpp>
#include <CLI11.hpp>
#include <iostream>
#include <string>
#include <vector>
@@ -14,8 +14,16 @@
int main(int argc, char** argv)
{
#ifdef _WIN32
auto curCP = GetConsoleOutputCP();
std::shared_ptr<void> recovery(nullptr, [curCP](void*) { SetConsoleOutputCP(curCP); });
SetConsoleOutputCP(CP_UTF8);
#endif
if (argc < 2) {
std::cout << "使用 --help 获取帮助信息。" << std::endl;
return 0;
}
CLI::App app{"百度翻译xlsx批量工具。"};
argv = app.ensure_utf8(argv);

View File

@@ -0,0 +1,8 @@
{
"baseUrl": "https://fanyi-api.baidu.com/api/trans/vip/translate?",
"appId": "463",
"appKey": "",
"appSecret": "HS0Ra2cvS5il3H",
"type": 0,
"interval": 200
}