HTTPClient.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  1. /**
  2. * @file HTTPClient.cpp
  3. * @brief implementation of the HTTP client class
  4. * @author Mohamed Amine Mzoughi <mohamed-amine.mzoughi@laposte.net>
  5. */
  6. #include "StdAfx.h"
  7. #include "HTTPClient.h"
  8. #include "json/json.h"
  9. #if defined(_MSC_VER)
  10. #else
  11. #include "toolkit.h"
  12. #include <winpr/string.h>
  13. #endif //_MSC_VER
  14. #define DEBUG_LOG(msg) \
  15. do { \
  16. if (m_eSettingsFlags & ENABLE_LOG) \
  17. m_oLog(msg); \
  18. } while (false)
  19. ///*TODO(80374374@3/9/2023): */
  20. GetTokenCallBack g_tokenCall = NULL;
  21. #ifndef _WIN32
  22. static toolkit_once_t once4curl = TOOLKIT_ONCE_INIT;
  23. class CLibCurlLifeManage
  24. {
  25. public:
  26. CLibCurlLifeManage() :bInited(false) {}
  27. void Init()
  28. {
  29. if (!bInited) {
  30. curl_global_init(CURL_GLOBAL_ALL);
  31. bInited = true;
  32. }
  33. }
  34. ~CLibCurlLifeManage()
  35. {
  36. if (bInited) {
  37. curl_global_cleanup();
  38. bInited = false;
  39. }
  40. }
  41. private:
  42. bool bInited;
  43. };
  44. static CLibCurlLifeManage gLibcurlMnt;
  45. static void init_libcurl_once(void)
  46. {
  47. gLibcurlMnt.Init();
  48. }
  49. #include "charset.h"
  50. static std::string GBK2UTF8(const std::string str)
  51. {
  52. std::string result("");
  53. if (str.empty())
  54. return result;
  55. if (toolkit_detect_utf8_str(str.c_str())) {
  56. result = str;
  57. } else {
  58. auto ret = toolkit_gbk2utf8((char*)str.c_str(), str.length(), NULL, 0);
  59. if (ret <= 0)
  60. return result;
  61. char* arr = new char[ret];
  62. ret = toolkit_gbk2utf8((char*)str.c_str(), str.length(), arr, ret);
  63. if (ret > 0) {
  64. result = arr;
  65. }
  66. delete[] arr;
  67. }
  68. return result;
  69. }
  70. static std::string UTF8ToGBK(const std::string str)
  71. {
  72. std::string result("");
  73. if (str.empty())
  74. return result;
  75. if (!toolkit_detect_utf8_str(str.c_str())) {
  76. result = str;
  77. } else {
  78. auto ret = toolkit_utf82gbk((char*)str.c_str(), str.length(), NULL, 0);
  79. if (ret <= 0)
  80. return result;
  81. char* arr = new char[ret];
  82. ret = toolkit_utf82gbk((char*)str.c_str(), str.length(), arr, ret);
  83. if (ret > 0) {
  84. result = arr;
  85. }
  86. delete[] arr;
  87. }
  88. return result;
  89. }
  90. void ConvertUtf8ToGBK(std::string& str)
  91. {
  92. const std::string result = UTF8ToGBK(str);
  93. str = result;
  94. }
  95. void ConvertGBKToUtf8(std::string& str)
  96. {
  97. const std::string result = GBK2UTF8(str);
  98. str = result;
  99. }
  100. #endif
  101. // Static members initialization
  102. volatile int CHTTPClient::s_iCurlSession = 0;
  103. std::string CHTTPClient::s_strCertificationAuthorityFile;
  104. HANDLE CHTTPClient::s_mtxCurlSession;
  105. HANDLE CHTTPClient::m_hLock;
  106. #ifdef DEBUG_CURL
  107. std::string CHTTPClient::s_strCurlTraceLogDirectory;
  108. #endif
  109. RVCCOMM_API void SetTokenCallBack(GetTokenCallBack t_callBack)
  110. {
  111. g_tokenCall = t_callBack;
  112. }
  113. BOOL CHTTPClient::Lock(DWORD dwTime)
  114. {
  115. // 如果还没有创建锁就先创建一个
  116. if (!m_hLock)
  117. {
  118. m_hLock = ::CreateMutex(NULL, FALSE, NULL);
  119. if (!m_hLock)
  120. return FALSE;
  121. }
  122. // 哪个线程最先调用等待函数就最先占用这个互斥量
  123. DWORD dwRet = ::WaitForSingleObject(m_hLock, dwTime);
  124. return (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_ABANDONED);
  125. }
  126. void CHTTPClient::Unlock()
  127. {
  128. if (m_hLock)
  129. ::ReleaseMutex(m_hLock);
  130. }
  131. /**
  132. * @brief constructor of the HTTP client object
  133. *
  134. * @param Logger - a callabck to a logger function void(const std::string&)
  135. *
  136. */
  137. CHTTPClient::CHTTPClient(LogFnCallback Logger) :
  138. m_oLog(Logger),
  139. m_iCurlTimeout(30),
  140. m_bHTTPS(false),
  141. m_bNoSignal(false),
  142. m_bProgressCallbackSet(false),
  143. m_eSettingsFlags(ENABLE_LOG),
  144. m_pCurlSession(nullptr),
  145. m_pHeaderlist(nullptr)
  146. {
  147. #if defined(_MSC_VER)
  148. Lock(INFINITE);
  149. if (s_iCurlSession++ == 0)
  150. {
  151. /* In windows, this will init the winsock stuff */
  152. curl_global_init(CURL_GLOBAL_ALL);
  153. }
  154. Unlock();
  155. #else
  156. toolkit_once(&once4curl, init_libcurl_once);
  157. #endif //RVC_OS_WIN
  158. InitSession(false, ENABLE_LOG);
  159. }
  160. /**
  161. * @brief destructor of the HTTP client object
  162. *
  163. */
  164. CHTTPClient::~CHTTPClient()
  165. {
  166. if (m_pCurlSession != nullptr)
  167. {
  168. CleanupSession();
  169. }
  170. #if defined(RVC_OS_WIN)
  171. DEBUG_LOG("to lock.");
  172. Lock(INFINITE);
  173. if (--s_iCurlSession <= 0) {
  174. DEBUG_LOG("to clean curl.");
  175. curl_global_cleanup();
  176. DEBUG_LOG("after clean curl.");
  177. }
  178. Unlock();
  179. DEBUG_LOG("unlock finished");
  180. #else
  181. #endif //RVC_OS_WIN
  182. }
  183. /**
  184. * @brief Starts a new HTTP session, initializes the cURL API session
  185. *
  186. * If a new session was already started, the method has no effect.
  187. *
  188. * @param [in] bHTTPS Enable/Disable HTTPS (disabled by default)
  189. * @param [in] eSettingsFlags optional use | operator to choose multiple options
  190. *
  191. * @retval true Successfully initialized the session.
  192. * @retval false The session is already initialized
  193. * Use CleanupSession() before initializing a new one or the Curl API is not initialized.
  194. *
  195. * Example Usage:
  196. * @code
  197. * m_pHTTPClient->InitSession();
  198. * @endcode
  199. */
  200. const bool CHTTPClient::InitSession(const bool& bHTTPS /* = false */,
  201. const SettingsFlag& eSettingsFlags /* = ALL_FLAGS */)
  202. {
  203. if (m_pCurlSession)
  204. {
  205. if (eSettingsFlags & ENABLE_LOG)
  206. m_oLog(LOG_ERROR_CURL_ALREADY_INIT_MSG);
  207. return false;
  208. }
  209. m_pCurlSession = curl_easy_init();
  210. curl_easy_setopt(m_pCurlSession, CURLOPT_FORBID_REUSE, 1); //避免大量的TCP连接保持在CLOSE_WAIT状态
  211. m_bHTTPS = bHTTPS;
  212. m_eSettingsFlags = eSettingsFlags;
  213. return (m_pCurlSession != nullptr);
  214. }
  215. /**
  216. * @brief Cleans the current HTTP session
  217. *
  218. * If a session was not already started, the method has no effect
  219. *
  220. * @retval true Successfully cleaned the current session.
  221. * @retval false The session is not already initialized.
  222. *
  223. * Example Usage:
  224. * @code
  225. * m_pHTTPClient->CleanupSession();
  226. * @endcode
  227. */
  228. const bool CHTTPClient::CleanupSession()
  229. {
  230. if (!m_pCurlSession)
  231. {
  232. if (m_eSettingsFlags & ENABLE_LOG)
  233. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  234. return false;
  235. }
  236. #ifdef DEBUG_CURL
  237. if (m_ofFileCurlTrace.is_open())
  238. {
  239. m_ofFileCurlTrace.close();
  240. }
  241. #endif
  242. curl_easy_cleanup(m_pCurlSession);
  243. m_pCurlSession = nullptr;
  244. if (m_pHeaderlist)
  245. {
  246. curl_slist_free_all(m_pHeaderlist);
  247. m_pHeaderlist = nullptr;
  248. }
  249. return true;
  250. }
  251. /**
  252. * @brief sets the progress function callback and the owner of the client
  253. *
  254. * @param [in] pOwner pointer to the object owning the client, nullptr otherwise
  255. * @param [in] fnCallback callback to progress function
  256. *
  257. */
  258. /*inline*/ void CHTTPClient::SetProgressFnCallback(void* pOwner, const ProgressFnCallback& fnCallback)
  259. {
  260. m_ProgressStruct.pOwner = pOwner;
  261. m_fnProgressCallback = fnCallback;
  262. m_ProgressStruct.pCurl = m_pCurlSession;
  263. m_ProgressStruct.dLastRunTime = 0;
  264. m_bProgressCallbackSet = true;
  265. }
  266. /**
  267. * @brief sets the HTTP Proxy address to tunnel the operation through it
  268. *
  269. * @param [in] strProxy URI of the HTTP Proxy
  270. *
  271. */
  272. /*inline*/ void CHTTPClient::SetProxy(const std::string& strProxy)
  273. {
  274. if (strProxy.empty())
  275. return;
  276. std::string strUri = strProxy;
  277. std::transform(strUri.begin(), strUri.end(), strUri.begin(), ::toupper);
  278. if (strUri.compare(0, 4, "HTTP") != 0)
  279. m_strProxy = "http://" + strProxy;
  280. else
  281. m_strProxy = strProxy;
  282. };
  283. /**
  284. * @brief checks a URI
  285. * adds the proper protocol scheme (HTTP:// or HTTPS://)
  286. * if the URI has no protocol scheme, the added protocol scheme
  287. * will depend on m_bHTTPS that can be set when initializing a session
  288. * or with the SetHTTPS(bool)
  289. *
  290. * @param [in] strURL user URI
  291. */
  292. inline void CHTTPClient::CheckURL(const std::string& strURL)
  293. {
  294. std::string strTmp = strURL;
  295. std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);
  296. if (strTmp.compare(0, 7, "HTTP://") == 0)
  297. m_bHTTPS = false;
  298. else if (strTmp.compare(0, 8, "HTTPS://") == 0)
  299. m_bHTTPS = true;
  300. else
  301. {
  302. m_strURL = ((m_bHTTPS) ? "https://" : "http://") + strURL;
  303. return;
  304. }
  305. m_strURL = strURL;
  306. }
  307. /**
  308. * @brief performs the chosen HTTP request
  309. * sets up the common settings (Timeout, proxy,...)
  310. *
  311. *
  312. * @retval true Successfully performed the request.
  313. * @retval false An error occured while CURL was performing the request.
  314. */
  315. const CURLcode CHTTPClient::Perform()
  316. {
  317. if (!m_pCurlSession)
  318. {
  319. if (m_eSettingsFlags & ENABLE_LOG)
  320. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  321. return CURLE_FAILED_INIT;
  322. }
  323. CURLcode res = CURLE_OK;
  324. curl_easy_setopt(m_pCurlSession, CURLOPT_URL, m_strURL.c_str());
  325. curl_easy_setopt(m_pCurlSession, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  326. if (m_pHeaderlist != nullptr)
  327. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPHEADER, m_pHeaderlist);
  328. curl_easy_setopt(m_pCurlSession, CURLOPT_USERAGENT, CLIENT_USERAGENT);
  329. curl_easy_setopt(m_pCurlSession, CURLOPT_AUTOREFERER, 1L);
  330. curl_easy_setopt(m_pCurlSession, CURLOPT_FOLLOWLOCATION, 1L);
  331. if (m_iCurlTimeout > 0)
  332. {
  333. curl_easy_setopt(m_pCurlSession, CURLOPT_TIMEOUT, m_iCurlTimeout);
  334. // don't want to get a sig alarm on timeout
  335. curl_easy_setopt(m_pCurlSession, CURLOPT_NOSIGNAL, 1L);
  336. }
  337. if (!m_strProxy.empty())
  338. {
  339. curl_easy_setopt(m_pCurlSession, CURLOPT_PROXY, m_strProxy.c_str());
  340. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPPROXYTUNNEL, 1L);
  341. }
  342. if (m_bNoSignal)
  343. {
  344. curl_easy_setopt(m_pCurlSession, CURLOPT_NOSIGNAL, 1L);
  345. }
  346. if (m_bProgressCallbackSet)
  347. {
  348. curl_easy_setopt(m_pCurlSession, CURLOPT_PROGRESSFUNCTION, GetProgressFnCallback());
  349. curl_easy_setopt(m_pCurlSession, CURLOPT_PROGRESSDATA, &m_ProgressStruct);
  350. curl_easy_setopt(m_pCurlSession, CURLOPT_NOPROGRESS, 0L);
  351. }
  352. // SSL
  353. if (m_bHTTPS)
  354. {
  355. curl_easy_setopt(m_pCurlSession, CURLOPT_USE_SSL, CURLUSESSL_ALL);
  356. }
  357. if (m_bHTTPS && !(m_eSettingsFlags & VERIFY_PEER)){
  358. curl_easy_setopt(m_pCurlSession, CURLOPT_SSL_VERIFYPEER, 0L);
  359. //m_oLog("不验证证书!");
  360. }
  361. else{
  362. //m_oLog("验证证书!");
  363. }
  364. if (m_bHTTPS && !(m_eSettingsFlags & VERIFY_HOST)){
  365. curl_easy_setopt(m_pCurlSession, CURLOPT_SSL_VERIFYHOST, 0L); // use 2L for strict name check
  366. }
  367. if (m_bHTTPS && !s_strCertificationAuthorityFile.empty())
  368. curl_easy_setopt(m_pCurlSession, CURLOPT_CAINFO, s_strCertificationAuthorityFile.c_str());
  369. if (m_bHTTPS && !m_strSSLCertFile.empty())
  370. curl_easy_setopt(m_pCurlSession, CURLOPT_SSLCERT, m_strSSLCertFile.c_str());
  371. if (m_bHTTPS && !m_strSSLKeyFile.empty())
  372. curl_easy_setopt(m_pCurlSession, CURLOPT_SSLKEY, m_strSSLKeyFile.c_str());
  373. if (m_bHTTPS && !m_strSSLKeyPwd.empty())
  374. curl_easy_setopt(m_pCurlSession, CURLOPT_KEYPASSWD, m_strSSLKeyPwd.c_str());
  375. #ifdef DEBUG_CURL
  376. StartCurlDebug();
  377. #endif
  378. // Perform the requested operation
  379. res = curl_easy_perform(m_pCurlSession);
  380. #ifdef DEBUG_CURL
  381. EndCurlDebug();
  382. #endif
  383. if (m_pHeaderlist)
  384. {
  385. curl_slist_free_all(m_pHeaderlist);
  386. m_pHeaderlist = nullptr;
  387. }
  388. return res;
  389. }
  390. /**
  391. * @brief requests the content of a URI
  392. *
  393. * @param [in] strURL URI of the remote location (with the file name).
  394. * @param [out] strOutput reference to an output string.
  395. * @param [out] lHTTPStatusCode HTTP Status code of the response.
  396. *
  397. * @retval true Successfully requested the URI.
  398. * @retval false Encountered a problem.
  399. *
  400. * Example Usage:
  401. * @code
  402. * std::string strWebPage;
  403. * long lHTTPStatusCode = 0;
  404. * m_pHTTOClient->GetText("https://www.google.com", strWebPage, lHTTPStatusCode);
  405. * @endcode
  406. */
  407. const bool CHTTPClient::GetText(const std::string& strURL,
  408. std::string& strOutput,
  409. long& lHTTPStatusCode)
  410. {
  411. if (strURL.empty())
  412. {
  413. if (m_eSettingsFlags & ENABLE_LOG)
  414. m_oLog(LOG_ERROR_EMPTY_HOST_MSG);
  415. return false;
  416. }
  417. if (!m_pCurlSession)
  418. {
  419. if (m_eSettingsFlags & ENABLE_LOG)
  420. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  421. return false;
  422. }
  423. // Reset is mandatory to avoid bad surprises
  424. curl_easy_reset(m_pCurlSession);
  425. CheckURL(strURL);
  426. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPGET, 1L);
  427. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, WriteInStringCallback);
  428. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &strOutput);
  429. CURLcode res = Perform();
  430. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &lHTTPStatusCode);
  431. // Check for errors
  432. if (res != CURLE_OK)
  433. {
  434. if (m_eSettingsFlags & ENABLE_LOG){
  435. char errMsg[1024] = {0};
  436. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REQ_FAILURE_FORMAT, m_strURL.c_str(), res, curl_easy_strerror(res), lHTTPStatusCode);
  437. m_oLog(errMsg);
  438. }
  439. return false;
  440. }
  441. return true;
  442. }
  443. /**
  444. * @brief Downloads a remote file to a local file.
  445. *
  446. * @param [in] strLocalFile Complete path of the local file to download.
  447. * @param [in] strURL URI of the remote location (with the file name).
  448. * @param [out] lHTTPStatusCode HTTP Status code of the response.
  449. *
  450. * @retval true Successfully downloaded the file.
  451. * @retval false The file couldn't be downloaded. Check the log messages for more information.
  452. */
  453. const bool CHTTPClient::DownloadFile(const std::string& strLocalFile,
  454. const std::string& strURL,
  455. long& lHTTPStatusCode)
  456. {
  457. if (strURL.empty() || strLocalFile.empty())
  458. return false;
  459. if (!m_pCurlSession)
  460. {
  461. if (m_eSettingsFlags & ENABLE_LOG)
  462. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  463. return false;
  464. }
  465. // Reset is mandatory to avoid bad surprises
  466. curl_easy_reset(m_pCurlSession);
  467. CheckURL(strURL);
  468. std::ofstream ofsOutput;
  469. ofsOutput.open(strLocalFile, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);
  470. if (ofsOutput)
  471. {
  472. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPGET, 1L);
  473. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, WriteToFileCallback);
  474. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &ofsOutput);
  475. CURLcode res = Perform();
  476. ofsOutput.close();
  477. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &lHTTPStatusCode);
  478. //double dUploadLength = 0;
  479. //curl_easy_getinfo(m_pCurlSession, CURLINFO_CONTENT_LENGTH_UPLOAD, &dUploadLength); // number of bytes uploaded
  480. /* Delete downloaded file if status code != 200 as server's response body may
  481. contain error 404 */
  482. if (lHTTPStatusCode != 200)
  483. remove(strLocalFile.c_str());
  484. if (res != CURLE_OK)
  485. {
  486. if (m_eSettingsFlags & ENABLE_LOG){
  487. char errMsg[1024] = {0};
  488. _snprintf(errMsg, 1023, LOG_ERROR_CURL_DOWNLOAD_FAILURE_FORMAT, strLocalFile.c_str(),
  489. strURL.c_str(), res, curl_easy_strerror(res), lHTTPStatusCode);
  490. m_oLog(errMsg);
  491. }
  492. return false;
  493. }
  494. }
  495. else if (m_eSettingsFlags & ENABLE_LOG)
  496. {
  497. char errMsg[1024] = {0};
  498. _snprintf(errMsg, 1023, LOG_ERROR_DOWNLOAD_FILE_FORMAT, strLocalFile.c_str());
  499. m_oLog(errMsg);
  500. return false;
  501. }
  502. return true;
  503. }
  504. /**
  505. * @brief uploads a POST form
  506. *
  507. *
  508. * @param [in] strURL URL to which the form will be posted.
  509. * @param [in] data post form information
  510. * @param [out] lHTTPStatusCode HTTP Status code of the response.
  511. *
  512. * @retval true Successfully posted the header.
  513. * @retval false The header couldn't be posted.
  514. */
  515. const bool CHTTPClient::UploadForm(const std::string& strURL,
  516. const PostFormInfo& data,
  517. long& lHTTPStatusCode)
  518. {
  519. if (strURL.empty())
  520. {
  521. if (m_eSettingsFlags & ENABLE_LOG)
  522. m_oLog(LOG_ERROR_EMPTY_HOST_MSG);
  523. return false;
  524. }
  525. if (!m_pCurlSession)
  526. {
  527. if (m_eSettingsFlags & ENABLE_LOG)
  528. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  529. return false;
  530. }
  531. // Reset is mandatory to avoid bad surprises
  532. curl_easy_reset(m_pCurlSession);
  533. CheckURL(strURL);
  534. /** Now specify we want to POST data */
  535. curl_easy_setopt(m_pCurlSession, CURLOPT_POST, 1L);
  536. /* stating that Expect: 100-continue is not wanted */
  537. AddHeader("Expect:");
  538. /** set post form */
  539. if (data.m_pFormPost != nullptr)
  540. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPPOST, data.m_pFormPost);
  541. /* to avoid printing response's body to stdout.
  542. * CURLOPT_WRITEDATA : by default, this is a FILE * to stdout. */
  543. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, ThrowAwayCallback);
  544. CURLcode res = Perform();
  545. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &lHTTPStatusCode);
  546. // Check for errors
  547. if (res != CURLE_OK)
  548. {
  549. if (m_eSettingsFlags & ENABLE_LOG)
  550. {
  551. char errMsg[1024] = {0};
  552. _snprintf(errMsg,1023, LOG_ERROR_CURL_REQ_FAILURE_FORMAT, m_strURL.c_str(), res,
  553. curl_easy_strerror(res), lHTTPStatusCode);
  554. m_oLog(errMsg);
  555. }
  556. return false;
  557. }
  558. return true;
  559. }
  560. /************************************************************************/
  561. /* add by cfq 添加文件块上传 */
  562. /************************************************************************/
  563. const bool CHTTPClient:: UploadFileBlock(CHTTPUploadReq &req, CHTTPUploadRet &ret)
  564. {
  565. if(req.url.empty()){
  566. if (m_eSettingsFlags & ENABLE_LOG)
  567. m_oLog(LOG_ERROR_EMPTY_HOST_MSG);
  568. return false;
  569. }
  570. if (!m_pCurlSession)
  571. {
  572. if (m_eSettingsFlags & ENABLE_LOG)
  573. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  574. return false;
  575. }
  576. // Reset is mandatory to avoid bad surprises
  577. curl_easy_reset(m_pCurlSession);
  578. CheckURL(req.url);
  579. if(req.m_printDbg){
  580. m_oLog(req.url.c_str());
  581. std::string msg = "是否是https请求:";
  582. msg.append(m_bHTTPS ? "true" : "false");
  583. m_oLog(msg.c_str());
  584. }
  585. /** Now specify we want to POST data */
  586. curl_easy_setopt(m_pCurlSession, CURLOPT_POST, 1L);
  587. /* stating that Expect: 100-continue is not wanted */
  588. AddHeader("Expect:");
  589. curl_httppost* pFormPost = NULL;
  590. curl_httppost* pLastFormptr = NULL;
  591. //添加参数
  592. if(req.m_bTransCode){
  593. if(req.m_printDbg){
  594. m_oLog("url转码 GBK=>UTF-8");
  595. }
  596. ConvertGBKToUtf8(req.paramContent); //转码
  597. }
  598. curl_formadd(&pFormPost, &pLastFormptr,
  599. CURLFORM_COPYNAME, "params",
  600. CURLFORM_COPYCONTENTS, req.paramContent.c_str(),
  601. CURLFORM_END);
  602. //添加文件流
  603. curl_formadd(&pFormPost, &pLastFormptr,
  604. CURLFORM_COPYNAME, "file_content",
  605. CURLFORM_BUFFER, req.fileName.c_str(),
  606. CURLFORM_BUFFERPTR, req.fileContent,
  607. CURLFORM_BUFFERLENGTH, req.fileContentSize,
  608. CURLFORM_CONTENTTYPE, "application/octet-stream",
  609. CURLFORM_END);
  610. /** set post form */
  611. if (pFormPost != nullptr)
  612. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPPOST, pFormPost);
  613. //接受响应body
  614. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, WriteInStringCallback);
  615. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &ret.strBody);
  616. //接受响应头
  617. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERFUNCTION, HeaderCallback);
  618. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERDATA, &ret.m_headers);
  619. //set timeout
  620. m_iCurlTimeout = req.m_timeOut;
  621. if(req.m_printDbg){
  622. m_oLog("开始发起上传请求!");
  623. }
  624. CURLcode res = Perform();
  625. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &ret.httpCode);
  626. curl_formfree(pFormPost);
  627. //添加参数
  628. if(req.m_bTransCode){
  629. if(req.m_printDbg){
  630. m_oLog("url转码 UTF-8=>GBK");
  631. }
  632. ConvertUtf8ToGBK(ret.strBody);
  633. }
  634. // Check for errors
  635. if (res != CURLE_OK)
  636. {
  637. ret.httpCode = -1;
  638. ret.strBody.clear();
  639. if (m_eSettingsFlags & ENABLE_LOG)
  640. {
  641. char errMsg[1024] = {0};
  642. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REQ_FAILURE_FORMAT, m_strURL.c_str(), res,
  643. curl_easy_strerror(res), ret.httpCode);
  644. m_oLog(errMsg);
  645. }
  646. return false;
  647. }
  648. else{
  649. if(req.m_printDbg){
  650. m_oLog("文件块上传成功!");
  651. }
  652. try
  653. {
  654. Json::Value root;
  655. Json::Reader reader;
  656. reader.parse(ret.strBody,root,false);
  657. if(root.isMember("code") && root.isMember("message"))
  658. {
  659. ret.m_userCode = root["code"].asString();
  660. ret.m_errMsg = root["message"].asString();
  661. return true;
  662. }
  663. else
  664. {
  665. char errMsg[1024] = {0};
  666. _snprintf(errMsg, 1023, LOG_ERROR_RESPONSE_FORMAT_FAILTURE_MSG, ret.strBody.c_str());
  667. ret.m_userCode = "0";
  668. ret.m_errMsg = "Unexpected format of stupid previous assuption!";
  669. return true;
  670. }
  671. }
  672. catch(...){
  673. m_oLog(LOG_ERROR_PARSE_JSON_FAILTURE_MSG);
  674. return false;
  675. }
  676. }
  677. return true;
  678. }
  679. /************************************************************************/
  680. /* add by cfq 添加文件块下载 */
  681. /************************************************************************/
  682. const bool CHTTPClient:: DownloadFileBlock(const char* url, const char* jsonReqStr, fileContentArray& content, long &httpCode, unordered_map<string, string>& responseHeaders, long timeout)
  683. {
  684. if (url == nullptr)
  685. return false;
  686. if (!m_pCurlSession)
  687. {
  688. if (m_eSettingsFlags & ENABLE_LOG)
  689. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  690. return false;
  691. }
  692. // Reset is mandatory to avoid bad surprises
  693. curl_easy_reset(m_pCurlSession);
  694. CheckURL(url);
  695. if(content.copyPtr != NULL){
  696. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPPOST, 1);
  697. curl_easy_setopt(m_pCurlSession, CURLOPT_POSTFIELDS, jsonReqStr);
  698. //接受响应头
  699. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERFUNCTION, HeaderCallback);
  700. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERDATA, &responseHeaders);
  701. *(content.curLen) = 0;
  702. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, WriteInByteCallback);
  703. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &content);
  704. m_iCurlTimeout = timeout;//下载读写数据超时
  705. AddHeader("Content-Type:application/json");
  706. CURLcode res = Perform();
  707. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &httpCode);
  708. // Check for errors
  709. if (res != CURLE_OK)
  710. {
  711. httpCode = -1;
  712. if (m_eSettingsFlags & ENABLE_LOG)
  713. {
  714. char errMsg[1024] = {0};
  715. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REQ_FAILURE_FORMAT, m_strURL.c_str(), res,
  716. curl_easy_strerror(res), httpCode);
  717. m_oLog(errMsg);
  718. }
  719. return false;
  720. }
  721. return true;
  722. }
  723. else{
  724. return false;
  725. }
  726. }
  727. /**
  728. * @brief PostFormInfo constructor
  729. */
  730. CHTTPClient::PostFormInfo::PostFormInfo() :
  731. m_pFormPost(nullptr), m_pLastFormptr(nullptr)
  732. {
  733. }
  734. /**
  735. * @brief PostFormInfo destructor
  736. */
  737. CHTTPClient::PostFormInfo::~PostFormInfo()
  738. {
  739. // cleanup the formpost chain
  740. if (m_pFormPost)
  741. {
  742. curl_formfree(m_pFormPost);
  743. m_pFormPost = nullptr;
  744. m_pLastFormptr = nullptr;
  745. }
  746. }
  747. /**
  748. * @brief set the name and the value of the HTML "file" form's input
  749. *
  750. * @param fieldName name of the "file" input
  751. * @param fieldValue path to the file to upload
  752. */
  753. void CHTTPClient::PostFormInfo::AddFormFile(const std::string& strFieldName,
  754. const std::string& strFieldValue)
  755. {
  756. curl_formadd(&m_pFormPost, &m_pLastFormptr,
  757. CURLFORM_COPYNAME, strFieldName.c_str(),
  758. CURLFORM_FILE, strFieldValue.c_str(),
  759. CURLFORM_END);
  760. }
  761. /**
  762. * @brief set the name and the value of an HTML form's input
  763. * (other than "file" like "text", "hidden" or "submit")
  764. *
  765. * @param fieldName name of the input element
  766. * @param fieldValue value to be assigned to the input element
  767. */
  768. void CHTTPClient::PostFormInfo::AddFormContent(const std::string& strFieldName,
  769. const std::string& strFieldValue)
  770. {
  771. curl_formadd(&m_pFormPost, &m_pLastFormptr,
  772. CURLFORM_COPYNAME, strFieldName.c_str(),
  773. CURLFORM_COPYCONTENTS, strFieldValue.c_str(),
  774. CURLFORM_END);
  775. }
  776. // REST REQUESTS
  777. /**
  778. * @brief initializes a REST request
  779. * some common operations to REST requests are performed here,
  780. * the others are performed in Perform method
  781. *
  782. * @param [in] Headers headers to send
  783. * @param [out] Response response data
  784. */
  785. inline const bool CHTTPClient::InitRestRequest(const std::string& strUrl,
  786. const CHTTPClient::HeadersMap& Headers,
  787. CHTTPClient::HttpResponse& Response)
  788. {
  789. if (strUrl.empty())
  790. {
  791. if (m_eSettingsFlags & ENABLE_LOG)
  792. m_oLog(LOG_ERROR_EMPTY_HOST_MSG);
  793. return false;
  794. }
  795. if (!m_pCurlSession)
  796. {
  797. if (m_eSettingsFlags & ENABLE_LOG)
  798. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  799. return false;
  800. }
  801. // Reset is mandatory to avoid bad surprises
  802. curl_easy_reset(m_pCurlSession);
  803. CheckURL(strUrl);
  804. // set the received body's callback function
  805. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, &CHTTPClient::RestWriteCallback);
  806. // set data object to pass to callback function above
  807. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &Response);
  808. // set the response's headers processing callback function
  809. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERFUNCTION, &CHTTPClient::RestHeaderCallback);
  810. // callback object for server's responses headers
  811. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERDATA, &Response);
  812. std::string strHeader;
  813. for (HeadersMap::const_iterator it = Headers.cbegin();
  814. it != Headers.cend();
  815. ++it)
  816. {
  817. strHeader = it->first + ": " + it->second; // build header string
  818. AddHeader(strHeader);
  819. }
  820. return true;
  821. }
  822. /**
  823. * @brief post REST request operations are performed here
  824. *
  825. * @param [in] ePerformCode curl easy perform returned code
  826. * @param [out] Response response data
  827. */
  828. inline const bool CHTTPClient::PostRestRequest(const CURLcode ePerformCode,
  829. CHTTPClient::HttpResponse& Response)
  830. {
  831. // Check for errors
  832. if (ePerformCode != CURLE_OK)
  833. {
  834. Response.strBody.clear();
  835. Response.iCode = -1;
  836. if (m_eSettingsFlags & ENABLE_LOG){
  837. char errMsg[1024] = {0};
  838. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REST_FAILURE_FORMAT, m_strURL.c_str(), ePerformCode,
  839. curl_easy_strerror(ePerformCode));
  840. m_oLog(errMsg);
  841. Response.iCode = ePerformCode;
  842. Response.strBody.append(errMsg);
  843. }
  844. return false;
  845. }
  846. long lHttpCode = 0;
  847. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &lHttpCode);
  848. Response.iCode = static_cast<int>(lHttpCode);
  849. return true;
  850. }
  851. /**
  852. * @brief performs a HEAD request
  853. *
  854. * @param [in] strUrl url to request
  855. * @param [in] Headers headers to send
  856. * @param [out] Response response data
  857. *
  858. * @retval true Successfully requested the URI.
  859. * @retval false Encountered a problem.
  860. */
  861. const bool CHTTPClient::Head(const std::string& strUrl,
  862. const CHTTPClient::HeadersMap& Headers,
  863. CHTTPClient::HttpResponse& Response)
  864. {
  865. if (InitRestRequest(strUrl, Headers, Response))
  866. {
  867. /** set HTTP HEAD METHOD */
  868. curl_easy_setopt(m_pCurlSession, CURLOPT_CUSTOMREQUEST, "HEAD");
  869. curl_easy_setopt(m_pCurlSession, CURLOPT_NOBODY, 1L);
  870. CURLcode res = Perform();
  871. return PostRestRequest(res, Response);
  872. }
  873. else
  874. return false;
  875. }
  876. /**
  877. * @brief performs a GET request
  878. *
  879. * @param [in] strUrl url to request
  880. * @param [in] Headers headers to send
  881. * @param [out] Response response data
  882. *
  883. * @retval true Successfully requested the URI.
  884. * @retval false Encountered a problem.
  885. */
  886. const bool CHTTPClient::Get(const std::string& strUrl,
  887. const CHTTPClient::HeadersMap& Headers,
  888. CHTTPClient::HttpResponse& Response)
  889. {
  890. if (InitRestRequest(strUrl, Headers, Response))
  891. {
  892. // specify a GET request
  893. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPGET, 1L);
  894. CURLcode res = Perform();
  895. return PostRestRequest(res, Response);
  896. }
  897. else
  898. return false;
  899. }
  900. /**
  901. * @brief performs a DELETE request
  902. *
  903. * @param [in] strUrl url to request
  904. * @param [in] Headers headers to send
  905. * @param [out] Response response data
  906. *
  907. * @retval true Successfully requested the URI.
  908. * @retval false Encountered a problem.
  909. */
  910. const bool CHTTPClient::Del(const std::string& strUrl,
  911. const CHTTPClient::HeadersMap& Headers,
  912. CHTTPClient::HttpResponse& Response)
  913. {
  914. if (InitRestRequest(strUrl, Headers, Response))
  915. {
  916. curl_easy_setopt(m_pCurlSession, CURLOPT_CUSTOMREQUEST, "DELETE");
  917. CURLcode res = Perform();
  918. return PostRestRequest(res, Response);
  919. }
  920. else
  921. return false;
  922. }
  923. const bool CHTTPClient::Post(const std::string& strUrl,
  924. const CHTTPClient::HeadersMap& Headers,
  925. const std::string& strPostData,
  926. CHTTPClient::HttpResponse& Response)
  927. {
  928. if (InitRestRequest(strUrl, Headers, Response))
  929. {
  930. // specify a POST request
  931. curl_easy_setopt(m_pCurlSession, CURLOPT_POST, 1L);
  932. // set post informations
  933. curl_easy_setopt(m_pCurlSession, CURLOPT_POSTFIELDS, strPostData.c_str());
  934. curl_easy_setopt(m_pCurlSession, CURLOPT_POSTFIELDSIZE, strPostData.size());
  935. CURLcode res = Perform();
  936. return PostRestRequest(res, Response);
  937. }
  938. else
  939. return false;
  940. }
  941. /**
  942. * @brief performs a PUT request with a string
  943. *
  944. * @param [in] strUrl url to request
  945. * @param [in] Headers headers to send
  946. * @param [out] Response response data
  947. *
  948. * @retval true Successfully requested the URI.
  949. * @retval false Encountered a problem.
  950. */
  951. const bool CHTTPClient::Put(const std::string& strUrl, const CHTTPClient::HeadersMap& Headers,
  952. const std::string& strPutData, CHTTPClient::HttpResponse& Response)
  953. {
  954. if (InitRestRequest(strUrl, Headers, Response))
  955. {
  956. CHTTPClient::UploadObject Payload;
  957. Payload.pszData = strPutData.c_str();
  958. Payload.usLength = strPutData.size();
  959. // specify a PUT request
  960. curl_easy_setopt(m_pCurlSession, CURLOPT_PUT, 1L);
  961. curl_easy_setopt(m_pCurlSession, CURLOPT_UPLOAD, 1L);
  962. // set read callback function
  963. curl_easy_setopt(m_pCurlSession, CURLOPT_READFUNCTION, &CHTTPClient::RestReadCallback);
  964. // set data object to pass to callback function
  965. curl_easy_setopt(m_pCurlSession, CURLOPT_READDATA, &Payload);
  966. // set data size
  967. curl_easy_setopt(m_pCurlSession, CURLOPT_INFILESIZE, static_cast<long>(Payload.usLength));
  968. CURLcode res = Perform();
  969. return PostRestRequest(res, Response);
  970. }
  971. else
  972. return false;
  973. }
  974. /**
  975. * @brief performs a PUT request with a byte buffer (vector of char)
  976. *
  977. * @param [in] strUrl url to request
  978. * @param [in] Headers headers to send
  979. * @param [out] Response response data
  980. *
  981. * @retval true Successfully requested the URI.
  982. * @retval false Encountered a problem.
  983. */
  984. const bool CHTTPClient::Put(const std::string& strUrl, const CHTTPClient::HeadersMap& Headers,
  985. const CHTTPClient::ByteBuffer& Data, CHTTPClient::HttpResponse& Response)
  986. {
  987. if (InitRestRequest(strUrl, Headers, Response))
  988. {
  989. CHTTPClient::UploadObject Payload;
  990. Payload.pszData = Data.data();
  991. Payload.usLength = Data.size();
  992. // specify a PUT request
  993. curl_easy_setopt(m_pCurlSession, CURLOPT_PUT, 1L);
  994. curl_easy_setopt(m_pCurlSession, CURLOPT_UPLOAD, 1L);
  995. // set read callback function
  996. curl_easy_setopt(m_pCurlSession, CURLOPT_READFUNCTION, &CHTTPClient::RestReadCallback);
  997. // set data object to pass to callback function
  998. curl_easy_setopt(m_pCurlSession, CURLOPT_READDATA, &Payload);
  999. // set data size
  1000. curl_easy_setopt(m_pCurlSession, CURLOPT_INFILESIZE, static_cast<long>(Payload.usLength));
  1001. CURLcode res = Perform();
  1002. return PostRestRequest(res, Response);
  1003. }
  1004. else
  1005. return false;
  1006. }
  1007. // STRING HELPERS
  1008. /**
  1009. * @brief returns a formatted string
  1010. *
  1011. * @param [in] strFormat string with one or many format specifiers
  1012. * @param [in] parameters to be placed in the format specifiers of strFormat
  1013. *
  1014. * @retval string formatted string
  1015. */
  1016. std::string CHTTPClient::StringFormat(const std::string strFormat, ...)
  1017. {
  1018. int n = (static_cast<int>(strFormat.size())) * 2; // Reserve two times as much as the length of the strFormat
  1019. std::unique_ptr<char[]> pFormatted;
  1020. va_list ap;
  1021. while(true)
  1022. {
  1023. pFormatted.reset(new char[n]); // Wrap the plain char array into the unique_ptr
  1024. strcpy(&pFormatted[0], strFormat.c_str());
  1025. va_start(ap, strFormat);
  1026. int iFinaln = vsnprintf(&pFormatted[0], n, strFormat.c_str(), ap);
  1027. va_end(ap);
  1028. if (iFinaln < 0 || iFinaln >= n)
  1029. {
  1030. n += abs(iFinaln - n + 1);
  1031. }
  1032. else
  1033. {
  1034. break;
  1035. }
  1036. }
  1037. return std::string(pFormatted.get());
  1038. }
  1039. /*std::string CHTTPClient::StringFormat(const std::string strFormat, ...)
  1040. {
  1041. char buffer[1024];
  1042. va_list args;
  1043. va_start(args, strFormat);
  1044. vsnprintf(buffer, 1024, strFormat.c_str(), args);
  1045. va_end (args);
  1046. return std::string(buffer);
  1047. }
  1048. */
  1049. /**
  1050. * @brief removes leading and trailing whitespace from a string
  1051. *
  1052. * @param [in/out] str string to be trimmed
  1053. */
  1054. inline void CHTTPClient::TrimSpaces(std::string& str)
  1055. {
  1056. // trim from left
  1057. str.erase(str.begin(),
  1058. std::find_if(str.begin(), str.end(), [](char c) {return !isspace(c); })
  1059. );
  1060. // trim from right
  1061. str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) {return !isspace(c); }).base(),
  1062. str.end()
  1063. );
  1064. }
  1065. // CURL CALLBACKS
  1066. size_t CHTTPClient::ThrowAwayCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1067. {
  1068. reinterpret_cast<void*>(ptr);
  1069. reinterpret_cast<void*>(data);
  1070. /* we are not interested in the headers itself,
  1071. so we only return the size we would have saved ... */
  1072. return size * nmemb;
  1073. }
  1074. /**
  1075. * @brief stores the server response in a string
  1076. *
  1077. * @param ptr pointer of max size (size*nmemb) to read data from it
  1078. * @param size size parameter
  1079. * @param nmemb memblock parameter
  1080. * @param data pointer to user data (string)
  1081. *
  1082. * @return (size * nmemb)
  1083. */
  1084. size_t CHTTPClient::WriteInStringCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1085. {
  1086. std::string* strWriteHere = reinterpret_cast<std::string*>(data);
  1087. if (strWriteHere != nullptr)
  1088. {
  1089. strWriteHere->append(reinterpret_cast<char*>(ptr), size * nmemb);
  1090. return size * nmemb;
  1091. }
  1092. return 0;
  1093. }
  1094. /**
  1095. * @brief stores the server response in an already opened file stream
  1096. * used by DownloadFile()
  1097. *
  1098. * @param buff pointer of max size (size*nmemb) to read data from it
  1099. * @param size size parameter
  1100. * @param nmemb memblock parameter
  1101. * @param userdata pointer to user data (file stream)
  1102. *
  1103. * @return (size * nmemb)
  1104. */
  1105. size_t CHTTPClient::WriteToFileCallback(void* buff, size_t size, size_t nmemb, void* data)
  1106. {
  1107. if ((size == 0) || (nmemb == 0) || ((size*nmemb) < 1) || (data == nullptr))
  1108. return 0;
  1109. std::ofstream* pFileStream = reinterpret_cast<std::ofstream*>(data);
  1110. if (pFileStream->is_open())
  1111. {
  1112. pFileStream->write(reinterpret_cast<char*>(buff), size * nmemb);
  1113. }
  1114. return size * nmemb;
  1115. }
  1116. /**
  1117. * @brief reads the content of an already opened file stream
  1118. * used by UploadFile()
  1119. *
  1120. * @param ptr pointer of max size (size*nmemb) to write data to it
  1121. * @param size size parameter
  1122. * @param nmemb memblock parameter
  1123. * @param stream pointer to user data (file stream)
  1124. *
  1125. * @return (size * nmemb)
  1126. */
  1127. size_t CHTTPClient::ReadFromFileCallback(void* ptr, size_t size, size_t nmemb, void* stream)
  1128. {
  1129. std::ifstream* pFileStream = reinterpret_cast<std::ifstream*>(stream);
  1130. if (pFileStream->is_open())
  1131. {
  1132. pFileStream->read(reinterpret_cast<char*>(ptr), size * nmemb);
  1133. return pFileStream->gcount();
  1134. }
  1135. return 0;
  1136. }
  1137. // REST CALLBACKS
  1138. /**
  1139. * @brief write callback function for libcurl
  1140. * this callback will be called to store the server's Body reponse
  1141. * in a struct response
  1142. *
  1143. * we can also use an std::vector<char> instead of an std::string but in this case
  1144. * there isn't a big difference... maybe resizing the container with a max size can
  1145. * enhance performances...
  1146. *
  1147. * @param data returned data of size (size*nmemb)
  1148. * @param size size parameter
  1149. * @param nmemb memblock parameter
  1150. * @param userdata pointer to user data to save/work with return data
  1151. *
  1152. * @return (size * nmemb)
  1153. */
  1154. size_t CHTTPClient::RestWriteCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1155. {
  1156. CHTTPClient::HttpResponse* pServerResponse;
  1157. pServerResponse = reinterpret_cast<CHTTPClient::HttpResponse*>(pUserData);
  1158. pServerResponse->strBody.append(reinterpret_cast<char*>(pCurlData), usBlockCount * usBlockSize);
  1159. return (usBlockCount * usBlockSize);
  1160. }
  1161. /**
  1162. * @brief header callback for libcurl
  1163. * callback used to process response's headers (received)
  1164. *
  1165. * @param data returned (header line)
  1166. * @param size of data
  1167. * @param nmemb memblock
  1168. * @param userdata pointer to user data object to save header data
  1169. * @return size * nmemb;
  1170. */
  1171. size_t CHTTPClient::RestHeaderCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1172. {
  1173. CHTTPClient::HttpResponse* pServerResponse;
  1174. pServerResponse = reinterpret_cast<CHTTPClient::HttpResponse*>(pUserData);
  1175. std::string strHeader(reinterpret_cast<char*>(pCurlData), usBlockCount * usBlockSize);
  1176. size_t usSeperator = strHeader.find_first_of(":");
  1177. if (std::string::npos == usSeperator)
  1178. {
  1179. //roll with non seperated headers or response's line
  1180. TrimSpaces(strHeader);
  1181. if (0 == strHeader.length())
  1182. {
  1183. return (usBlockCount * usBlockSize); //blank line;
  1184. }
  1185. pServerResponse->mapHeaders[strHeader] = "present";
  1186. }
  1187. else
  1188. {
  1189. std::string strKey = strHeader.substr(0, usSeperator);
  1190. TrimSpaces(strKey);
  1191. std::string strValue = strHeader.substr(usSeperator + 1);
  1192. TrimSpaces(strValue);
  1193. pServerResponse->mapHeaders[strKey] = strValue;
  1194. }
  1195. return (usBlockCount * usBlockSize);
  1196. }
  1197. size_t CHTTPClient::HeaderCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1198. {
  1199. CHTTPClient::HeadersMap *pheaderMap;
  1200. pheaderMap = reinterpret_cast<CHTTPClient::HeadersMap*>(pUserData);
  1201. std::string strHeader(reinterpret_cast<char*>(pCurlData), usBlockCount * usBlockSize);
  1202. size_t usSeperator = strHeader.find_first_of(":");
  1203. if (std::string::npos == usSeperator)
  1204. {
  1205. //roll with non seperated headers or response's line
  1206. TrimSpaces(strHeader);
  1207. if (0 == strHeader.length())
  1208. {
  1209. return (usBlockCount * usBlockSize); //blank line;
  1210. }
  1211. (*pheaderMap)[strHeader] = "present";
  1212. }
  1213. else
  1214. {
  1215. std::string strKey = strHeader.substr(0, usSeperator);
  1216. TrimSpaces(strKey);
  1217. std::string strValue = strHeader.substr(usSeperator + 1);
  1218. TrimSpaces(strValue);
  1219. (*pheaderMap)[strKey] = strValue;
  1220. }
  1221. return (usBlockCount * usBlockSize);
  1222. }
  1223. size_t CHTTPClient:: WriteInByteCallback(void* ptr, size_t size, size_t nmemb, void* pUserData)
  1224. {
  1225. fileContentArray *wbyte = reinterpret_cast<fileContentArray*>(pUserData);
  1226. if (wbyte == NULL || wbyte->copyPtr == NULL) {
  1227. return -1;
  1228. }
  1229. else {
  1230. size_t len = size * nmemb;
  1231. *(wbyte->curLen) += len;
  1232. if (len != 0 && *(wbyte->curLen) <= wbyte->maxLen) {
  1233. memcpy(wbyte->copyPtr, ptr, len);
  1234. wbyte->copyPtr += len;//移动指针
  1235. return len;
  1236. }
  1237. else {
  1238. return -2;
  1239. }
  1240. }
  1241. }
  1242. /**
  1243. * @brief read callback function for libcurl
  1244. * used to send (or upload) a content to the server
  1245. *
  1246. * @param pointer of max size (size*nmemb) to write data to (used by cURL to send data)
  1247. * @param size size parameter
  1248. * @param nmemb memblock parameter
  1249. * @param userdata pointer to user data to read data from
  1250. *
  1251. * @return (size * nmemb)
  1252. */
  1253. size_t CHTTPClient::RestReadCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1254. {
  1255. // get upload struct
  1256. CHTTPClient::UploadObject* Payload;
  1257. Payload = reinterpret_cast<CHTTPClient::UploadObject*>(pUserData);
  1258. // set correct sizes
  1259. size_t usCurlSize = usBlockCount * usBlockSize;
  1260. size_t usCopySize = (Payload->usLength < usCurlSize) ? Payload->usLength : usCurlSize;
  1261. /** copy data to buffer */
  1262. std::memcpy(pCurlData, Payload->pszData, usCopySize);
  1263. // decrement length and increment data pointer
  1264. Payload->usLength -= usCopySize; // remaining bytes to be sent
  1265. Payload->pszData += usCopySize; // next byte to the chunk that will be sent
  1266. /** return copied size */
  1267. return usCopySize;
  1268. }
  1269. //add by cfq
  1270. const bool CHTTPClient::Get(CHTTPReq &req, CHTTPRet &ret){
  1271. //拼接请求参数
  1272. string param;
  1273. std::string jsonStr="";
  1274. try
  1275. {
  1276. jsonStr= req.ToJson();
  1277. }
  1278. catch (...)
  1279. {
  1280. m_oLog(LOG_ERROR_GET_JSON_FAILTURE_MSG);
  1281. }
  1282. if(jsonStr.empty())
  1283. {
  1284. param = "";
  1285. }
  1286. else
  1287. {
  1288. Json::Value root;
  1289. Json::Reader reader;
  1290. reader.parse(jsonStr,root,false);
  1291. Json::Value::Members mem = root.getMemberNames();
  1292. for(auto iter = mem.begin(); iter != mem.end(); iter++){
  1293. switch(root[*iter].type()){
  1294. case Json::intValue:
  1295. char a[20];
  1296. _snprintf(a, sizeof(a), "%d", root[*iter].asInt());
  1297. param = param.append((*iter).c_str()).append("=").append(a);
  1298. break;
  1299. case Json::stringValue:
  1300. param = param.append((*iter).c_str()).append("=").append(root[*iter].asCString());
  1301. break;
  1302. case Json::realValue:
  1303. char b[20];
  1304. _snprintf(b, sizeof(b), "%.21f", root[*iter].asDouble());
  1305. param = param.append((*iter).c_str()).append("=").append(b);
  1306. break;
  1307. case Json::booleanValue:
  1308. param = param.append((*iter).c_str()).append("=").append(root[*iter].asBool() ? "true": "false");
  1309. break;
  1310. default:
  1311. break;
  1312. }
  1313. if((iter + 1) != mem.end()){
  1314. param = param.append("&");
  1315. }
  1316. //root.clear();
  1317. }
  1318. }
  1319. char requestData[20000];
  1320. _snprintf(requestData, sizeof(requestData), "%s", param.c_str());
  1321. if(req.m_printDbg){
  1322. m_oLog(requestData);
  1323. }
  1324. //urlEncode
  1325. char *requestData_encode = curl_easy_escape(m_pCurlSession, requestData, 0);
  1326. if(req.m_printDbg){
  1327. string str;
  1328. str.append("queryString encode:");
  1329. str.append(requestData);
  1330. m_oLog(str.c_str());
  1331. }
  1332. if(!req.m_url.empty()){
  1333. char *url = new char[req.m_url.length()+param.length()+2];
  1334. _snprintf(url, req.m_url.length()+param.length()+1, "%s?%s", req.m_url.c_str(), param.c_str());
  1335. m_oLog(url);
  1336. delete[] url;
  1337. }
  1338. else{
  1339. m_oLog(LOG_ERROR_PATH_NULL_MSG);
  1340. return false;
  1341. }
  1342. if(req.m_headers.empty()){
  1343. if(req.m_printDbg){
  1344. m_oLog("没有指定请求头内容,使用默认值Accept=application/json");
  1345. }
  1346. req.m_headers.emplace(std::make_pair("Accept", "application/json"));
  1347. }
  1348. if (req.m_withToken && g_tokenCall != NULL)
  1349. {
  1350. std::string channelId = "";
  1351. std::string token = "";
  1352. std::string terminalno = "";
  1353. std::string reserve1 = "";
  1354. g_tokenCall(channelId, token, terminalno, reserve1);
  1355. if (channelId.length() != 0 && token.length() != 0)
  1356. {
  1357. req.m_headers.emplace(std::make_pair("channelId", channelId));
  1358. req.m_headers.emplace(std::make_pair("token", token));
  1359. req.m_headers.emplace(std::make_pair("terminalno", terminalno));
  1360. string out = "channelId:" + channelId + ", token:" + token;
  1361. if (req.m_printDbg)
  1362. m_oLog(out.c_str());
  1363. }
  1364. }
  1365. //set timeout
  1366. m_iCurlTimeout = req.m_timeOut;
  1367. CHTTPClient::HttpResponse g_Response;
  1368. int nLen = 0;
  1369. string url = req.m_url + "?" + param;
  1370. if(req.m_bTransCode){
  1371. if(req.m_printDbg)
  1372. m_oLog("url转码 GBK=>UTF-8");
  1373. ConvertGBKToUtf8(url);
  1374. }
  1375. bool isSuccess = Get(url, req.m_headers, g_Response);
  1376. //转码
  1377. if(req.m_bTransCode){
  1378. if(req.m_printDbg)
  1379. m_oLog("responseData转码 UTF-8=>GBK");
  1380. ConvertUtf8ToGBK(g_Response.strBody);
  1381. }
  1382. if(req.m_printDbg){
  1383. std::string msg = "是否是https请求:";
  1384. msg.append(m_bHTTPS ? "true" : "false");
  1385. m_oLog(msg.c_str());
  1386. }
  1387. //处理响应值
  1388. ret.m_sysCode = g_Response.iCode;
  1389. ret.m_resultData = g_Response.strBody;
  1390. if(isSuccess == false || (g_Response.iCode != 200 && g_Response.iCode != 201)){
  1391. ret.m_errMsg = g_Response.strBody;
  1392. char errMsg[1024] = {0};
  1393. _snprintf(errMsg, 1023, "http请求报错,错误码:%d", g_Response.iCode);
  1394. m_oLog(errMsg);
  1395. return false;
  1396. }
  1397. else
  1398. {
  1399. if(req.m_printDbg)
  1400. m_oLog("http请求成功,开始解析json");
  1401. try
  1402. {
  1403. Json::Value root;
  1404. Json::Reader reader;
  1405. reader.parse(g_Response.strBody,root,false);
  1406. if(root.isMember("code") && root.isMember("message"))
  1407. {
  1408. ret.m_userCode = root["code"].asString();
  1409. ret.m_errMsg = root["message"].asString();
  1410. return ret.Parse(g_Response.strBody);
  1411. }
  1412. else
  1413. {
  1414. char errMsg[1024] = {0};
  1415. _snprintf(errMsg, 1023, LOG_ERROR_RESPONSE_FORMAT_FAILTURE_MSG, g_Response.strBody.c_str());
  1416. ret.m_userCode = "0";
  1417. ret.m_errMsg = "Unexpected format of stupid previous assuption!";
  1418. return true;
  1419. }
  1420. }
  1421. catch(...){
  1422. m_oLog(LOG_ERROR_PARSE_JSON_FAILTURE_MSG);
  1423. return false;
  1424. }
  1425. }
  1426. }
  1427. //add by cfq
  1428. const bool CHTTPClient::Post(CHTTPReq &req, CHTTPRet &ret){
  1429. if(!req.m_url.empty()){
  1430. if(req.m_printDbg){
  1431. char *url = new char[req.m_url.length() + 1];
  1432. memset(url, 0, req.m_url.length() + 1);
  1433. _snprintf(url, req.m_url.length(), "%s", req.m_url.c_str());
  1434. m_oLog(url);
  1435. delete[] url;
  1436. }
  1437. }
  1438. else{
  1439. m_oLog(LOG_ERROR_PATH_NULL_MSG);
  1440. return false;
  1441. }
  1442. std::string request;
  1443. try
  1444. {
  1445. request= req.ToJson();
  1446. }
  1447. catch (...)
  1448. {
  1449. m_oLog(LOG_ERROR_GET_JSON_FAILTURE_MSG);
  1450. }
  1451. //转码
  1452. if(req.m_bTransCode){
  1453. if(req.m_printDbg){
  1454. m_oLog("url转码 GBK=>UTF-8");
  1455. }
  1456. ConvertGBKToUtf8(request);
  1457. }
  1458. if(req.m_printDbg){
  1459. std:string msg = "strPostDate:";
  1460. msg.append(request);
  1461. m_oLog(msg.c_str());
  1462. }
  1463. if(req.m_headers.empty()){
  1464. if(req.m_printDbg){
  1465. m_oLog("没有指定请求头内容,使用默认值Content-Type=application/json");
  1466. }
  1467. req.m_headers.emplace(std::make_pair("Content-Type", "application/json"));
  1468. }
  1469. if (req.m_withToken && g_tokenCall != NULL)
  1470. {
  1471. std::string channelId = "";
  1472. std::string token = "";
  1473. std::string terminalno = "";
  1474. std::string reserve1 = "";
  1475. g_tokenCall(channelId, token, terminalno, reserve1);
  1476. if (channelId.length() != 0 && token.length() != 0)
  1477. {
  1478. req.m_headers.emplace(std::make_pair("channelId", channelId));
  1479. req.m_headers.emplace(std::make_pair("token", token));
  1480. req.m_headers.emplace(std::make_pair("terminalno", terminalno));
  1481. string out = "channelId:" + channelId + ", token:" + token;
  1482. if (req.m_printDbg)
  1483. m_oLog(out.c_str());
  1484. }
  1485. }
  1486. //set timeout
  1487. m_iCurlTimeout = req.m_timeOut;
  1488. CHTTPClient::HttpResponse g_Response;
  1489. bool isSuccess = Post(req.m_url, req.m_headers, request, g_Response);
  1490. //转码
  1491. if(req.m_bTransCode){
  1492. if(req.m_printDbg){
  1493. m_oLog("url转码 GBK=>UTF-8");
  1494. }
  1495. ConvertUtf8ToGBK(g_Response.strBody);
  1496. }
  1497. if(req.m_printDbg){
  1498. std::string msg = "是否是https请求:";
  1499. msg.append(m_bHTTPS ? "true" : "false");
  1500. m_oLog(msg.c_str());
  1501. }
  1502. //处理响应值
  1503. ret.m_sysCode = g_Response.iCode;
  1504. ret.m_resultData = g_Response.strBody;
  1505. if(isSuccess == false || (g_Response.iCode != 200 && g_Response.iCode != 201)){
  1506. ret.m_errMsg = g_Response.strBody;
  1507. char errMsg[1024] = {0};
  1508. _snprintf(errMsg, 1023, "http请求报错,错误码:%d", g_Response.iCode);
  1509. m_oLog(errMsg);
  1510. return false;
  1511. }
  1512. else
  1513. {
  1514. if(req.m_printDbg){
  1515. m_oLog("http请求成功,开始解析json");
  1516. }
  1517. try
  1518. {
  1519. Json::Value root;
  1520. Json::Reader reader;
  1521. reader.parse(g_Response.strBody,root,false);
  1522. if(root.isMember("code") && root.isMember("message"))
  1523. {
  1524. ret.m_userCode = root["code"].asString();
  1525. ret.m_errMsg = root["message"].asString();
  1526. return ret.Parse(g_Response.strBody);
  1527. }
  1528. else
  1529. {
  1530. char errMsg[1024] = {0};
  1531. _snprintf(errMsg, 1023, LOG_ERROR_RESPONSE_FORMAT_FAILTURE_MSG, g_Response.strBody.c_str());
  1532. ret.m_userCode = "0";
  1533. ret.m_errMsg = "Unexpected format of stupid previous assuption!";
  1534. return true;
  1535. }
  1536. }
  1537. catch(...){
  1538. m_oLog(LOG_ERROR_PARSE_JSON_FAILTURE_MSG);
  1539. return false;
  1540. }
  1541. }
  1542. }
  1543. // CURL DEBUG INFO CALLBACKS
  1544. #ifdef DEBUG_CURL
  1545. void CHTTPClient::SetCurlTraceLogDirectory(const std::string& strPath)
  1546. {
  1547. s_strCurlTraceLogDirectory = strPath;
  1548. if (!s_strCurlTraceLogDirectory.empty()
  1549. #ifdef WINDOWS
  1550. && s_strCurlTraceLogDirectory.at(s_strCurlTraceLogDirectory.length() - 1) != '\\')
  1551. {
  1552. s_strCurlTraceLogDirectory += '\\';
  1553. }
  1554. #else
  1555. && s_strCurlTraceLogDirectory.at(s_strCurlTraceLogDirectory.length() - 1) != '/')
  1556. {
  1557. s_strCurlTraceLogDirectory += '/';
  1558. }
  1559. #endif
  1560. }
  1561. int CHTTPClient::DebugCallback(CURL* curl, curl_infotype curl_info_type, char* pszTrace, size_t usSize, void* pFile)
  1562. {
  1563. std::string strText;
  1564. std::string strTrace(pszTrace, usSize);
  1565. switch (curl_info_type)
  1566. {
  1567. case CURLINFO_TEXT:
  1568. strText = "# Information : ";
  1569. break;
  1570. case CURLINFO_HEADER_OUT:
  1571. strText = "-> Sending header : ";
  1572. break;
  1573. case CURLINFO_DATA_OUT:
  1574. strText = "-> Sending data : ";
  1575. break;
  1576. case CURLINFO_SSL_DATA_OUT:
  1577. strText = "-> Sending SSL data : ";
  1578. break;
  1579. case CURLINFO_HEADER_IN:
  1580. strText = "<- Receiving header : ";
  1581. break;
  1582. case CURLINFO_DATA_IN:
  1583. strText = "<- Receiving unencrypted data : ";
  1584. break;
  1585. case CURLINFO_SSL_DATA_IN:
  1586. strText = "<- Receiving SSL data : ";
  1587. break;
  1588. default:
  1589. break;
  1590. }
  1591. std::ofstream* pofTraceFile = reinterpret_cast<std::ofstream*>(pFile);
  1592. if (pofTraceFile == nullptr)
  1593. {
  1594. std::cout << "[DEBUG] cURL debug log [" << curl_info_type << "]: " << " - " << strTrace;
  1595. }
  1596. else
  1597. {
  1598. (*pofTraceFile) << strText << strTrace;
  1599. }
  1600. return 0;
  1601. }
  1602. void CHTTPClient::StartCurlDebug() const
  1603. {
  1604. if (!m_ofFileCurlTrace.is_open())
  1605. {
  1606. curl_easy_setopt(m_pCurlSession, CURLOPT_VERBOSE, 1L);
  1607. curl_easy_setopt(m_pCurlSession, CURLOPT_DEBUGFUNCTION, DebugCallback);
  1608. std::string strFileCurlTraceFullName(s_strCurlTraceLogDirectory);
  1609. if (!strFileCurlTraceFullName.empty())
  1610. {
  1611. char szDate[32];
  1612. memset(szDate, 0, 32);
  1613. time_t tNow; time(&tNow);
  1614. // new trace file for each hour
  1615. strftime(szDate, 32, "%Y%m%d_%H", localtime(&tNow));
  1616. strFileCurlTraceFullName += "TraceLog_";
  1617. strFileCurlTraceFullName += szDate;
  1618. strFileCurlTraceFullName += ".txt";
  1619. m_ofFileCurlTrace.open(strFileCurlTraceFullName, std::ifstream::app | std::ifstream::binary);
  1620. if (m_ofFileCurlTrace)
  1621. curl_easy_setopt(m_pCurlSession, CURLOPT_DEBUGDATA, &m_ofFileCurlTrace);
  1622. }
  1623. }
  1624. }
  1625. void CHTTPClient::EndCurlDebug() const
  1626. {
  1627. if (m_ofFileCurlTrace && m_ofFileCurlTrace.is_open())
  1628. {
  1629. m_ofFileCurlTrace << "###########################################" << std::endl;
  1630. m_ofFileCurlTrace.close();
  1631. }
  1632. }
  1633. #endif