HTTPClient.cpp 52 KB

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