HTTPClient.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954
  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, HttpClientTraceLink* pTrace)
  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. unordered_map<string, string> m_headers;
  588. if (pTrace != NULL
  589. && strlen(pTrace->X_B3_BusinessId) > 0
  590. && strlen(pTrace->X_B3_TraceId) > 0
  591. && strlen(pTrace->X_B3_SpanId) > 0
  592. && strlen(pTrace->X_B3_ParentSpanId) > 0
  593. && strlen(pTrace->X_B3_Timestamp) > 0)
  594. {
  595. m_headers.emplace(std::make_pair("X_B3_BusinessId", pTrace->X_B3_BusinessId));
  596. m_headers.emplace(std::make_pair("X_B3_TraceId", pTrace->X_B3_TraceId));
  597. m_headers.emplace(std::make_pair("X_B3_SpanId", pTrace->X_B3_SpanId));
  598. m_headers.emplace(std::make_pair("X_B3_ParentSpanId", pTrace->X_B3_ParentSpanId));
  599. m_headers.emplace(std::make_pair("X_B3_Timestamp", pTrace->X_B3_Timestamp));
  600. }
  601. std::string strHeader;
  602. for (HeadersMap::const_iterator it = m_headers.cbegin();
  603. it != m_headers.cend();
  604. ++it)
  605. {
  606. strHeader = it->first + ": " + it->second; // build header string
  607. AddHeader(strHeader);
  608. }
  609. /* stating that Expect: 100-continue is not wanted */
  610. AddHeader("Expect:");
  611. curl_httppost* pFormPost = NULL;
  612. curl_httppost* pLastFormptr = NULL;
  613. //添加参数
  614. if(req.m_bTransCode){
  615. if(req.m_printDbg){
  616. m_oLog("url转码 GBK=>UTF-8");
  617. }
  618. ConvertGBKToUtf8(req.paramContent); //转码
  619. }
  620. curl_formadd(&pFormPost, &pLastFormptr,
  621. CURLFORM_COPYNAME, "params",
  622. CURLFORM_COPYCONTENTS, req.paramContent.c_str(),
  623. CURLFORM_END);
  624. //添加文件流
  625. curl_formadd(&pFormPost, &pLastFormptr,
  626. CURLFORM_COPYNAME, "file_content",
  627. CURLFORM_BUFFER, req.fileName.c_str(),
  628. CURLFORM_BUFFERPTR, req.fileContent,
  629. CURLFORM_BUFFERLENGTH, req.fileContentSize,
  630. CURLFORM_CONTENTTYPE, "application/octet-stream",
  631. CURLFORM_END);
  632. /** set post form */
  633. if (pFormPost != nullptr)
  634. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPPOST, pFormPost);
  635. //接受响应body
  636. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, WriteInStringCallback);
  637. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &ret.strBody);
  638. //接受响应头
  639. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERFUNCTION, HeaderCallback);
  640. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERDATA, &ret.m_headers);
  641. //set timeout
  642. m_iCurlTimeout = req.m_timeOut;
  643. if(req.m_printDbg){
  644. m_oLog("开始发起上传请求!");
  645. }
  646. CURLcode res = Perform();
  647. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &ret.httpCode);
  648. curl_formfree(pFormPost);
  649. //添加参数
  650. if(req.m_bTransCode){
  651. if(req.m_printDbg){
  652. m_oLog("url转码 UTF-8=>GBK");
  653. }
  654. ConvertUtf8ToGBK(ret.strBody);
  655. }
  656. // Check for errors
  657. if (res != CURLE_OK)
  658. {
  659. ret.httpCode = -1;
  660. ret.strBody.clear();
  661. if (m_eSettingsFlags & ENABLE_LOG)
  662. {
  663. char errMsg[1024] = {0};
  664. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REQ_FAILURE_FORMAT, m_strURL.c_str(), res,
  665. curl_easy_strerror(res), ret.httpCode);
  666. m_oLog(errMsg);
  667. }
  668. return false;
  669. }
  670. else{
  671. if(req.m_printDbg){
  672. m_oLog("文件块上传成功!");
  673. }
  674. try
  675. {
  676. Json::Value root;
  677. Json::Reader reader;
  678. reader.parse(ret.strBody,root,false);
  679. if(root.isMember("code") && root.isMember("message"))
  680. {
  681. ret.m_userCode = root["code"].asString();
  682. ret.m_errMsg = root["message"].asString();
  683. return true;
  684. }
  685. else
  686. {
  687. char errMsg[1024] = {0};
  688. _snprintf(errMsg, 1023, LOG_ERROR_RESPONSE_FORMAT_FAILTURE_MSG, ret.strBody.c_str());
  689. ret.m_userCode = "0";
  690. ret.m_errMsg = "Unexpected format of stupid previous assuption!";
  691. return true;
  692. }
  693. }
  694. catch(...){
  695. m_oLog(LOG_ERROR_PARSE_JSON_FAILTURE_MSG);
  696. return false;
  697. }
  698. }
  699. return true;
  700. }
  701. /************************************************************************/
  702. /* add by cfq 添加文件块下载 */
  703. /************************************************************************/
  704. const bool CHTTPClient:: DownloadFileBlock(const char* url, const char* jsonReqStr, fileContentArray& content, long &httpCode, unordered_map<string, string>& responseHeaders, long timeout, HttpClientTraceLink* pTrace)
  705. {
  706. if (url == nullptr)
  707. return false;
  708. if (!m_pCurlSession)
  709. {
  710. if (m_eSettingsFlags & ENABLE_LOG)
  711. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  712. return false;
  713. }
  714. // Reset is mandatory to avoid bad surprises
  715. curl_easy_reset(m_pCurlSession);
  716. CheckURL(url);
  717. if(content.copyPtr != NULL){
  718. // Add headers
  719. unordered_map<string, string> m_headers;
  720. if (pTrace != NULL
  721. && strlen(pTrace->X_B3_BusinessId) > 0
  722. && strlen(pTrace->X_B3_TraceId) > 0
  723. && strlen(pTrace->X_B3_SpanId) > 0
  724. && strlen(pTrace->X_B3_ParentSpanId) > 0
  725. && strlen(pTrace->X_B3_Timestamp) > 0)
  726. {
  727. m_headers.emplace(std::make_pair("X_B3_BusinessId", pTrace->X_B3_BusinessId));
  728. m_headers.emplace(std::make_pair("X_B3_TraceId", pTrace->X_B3_TraceId));
  729. m_headers.emplace(std::make_pair("X_B3_SpanId", pTrace->X_B3_SpanId));
  730. m_headers.emplace(std::make_pair("X_B3_ParentSpanId", pTrace->X_B3_ParentSpanId));
  731. m_headers.emplace(std::make_pair("X_B3_Timestamp", pTrace->X_B3_Timestamp));
  732. }
  733. std::string strHeader;
  734. for (HeadersMap::const_iterator it = m_headers.cbegin();
  735. it != m_headers.cend();
  736. ++it)
  737. {
  738. strHeader = it->first + ": " + it->second; // build header string
  739. AddHeader(strHeader);
  740. }
  741. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPPOST, 1);
  742. curl_easy_setopt(m_pCurlSession, CURLOPT_POSTFIELDS, jsonReqStr);
  743. //接受响应头
  744. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERFUNCTION, HeaderCallback);
  745. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERDATA, &responseHeaders);
  746. *(content.curLen) = 0;
  747. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, WriteInByteCallback);
  748. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &content);
  749. m_iCurlTimeout = timeout;//下载读写数据超时
  750. AddHeader("Content-Type:application/json");
  751. CURLcode res = Perform();
  752. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &httpCode);
  753. // Check for errors
  754. if (res != CURLE_OK)
  755. {
  756. httpCode = -1;
  757. if (m_eSettingsFlags & ENABLE_LOG)
  758. {
  759. char errMsg[1024] = {0};
  760. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REQ_FAILURE_FORMAT, m_strURL.c_str(), res,
  761. curl_easy_strerror(res), httpCode);
  762. m_oLog(errMsg);
  763. }
  764. return false;
  765. }
  766. return true;
  767. }
  768. else{
  769. return false;
  770. }
  771. }
  772. /**
  773. * @brief PostFormInfo constructor
  774. */
  775. CHTTPClient::PostFormInfo::PostFormInfo() :
  776. m_pFormPost(nullptr), m_pLastFormptr(nullptr)
  777. {
  778. }
  779. /**
  780. * @brief PostFormInfo destructor
  781. */
  782. CHTTPClient::PostFormInfo::~PostFormInfo()
  783. {
  784. // cleanup the formpost chain
  785. if (m_pFormPost)
  786. {
  787. curl_formfree(m_pFormPost);
  788. m_pFormPost = nullptr;
  789. m_pLastFormptr = nullptr;
  790. }
  791. }
  792. /**
  793. * @brief set the name and the value of the HTML "file" form's input
  794. *
  795. * @param fieldName name of the "file" input
  796. * @param fieldValue path to the file to upload
  797. */
  798. void CHTTPClient::PostFormInfo::AddFormFile(const std::string& strFieldName,
  799. const std::string& strFieldValue)
  800. {
  801. curl_formadd(&m_pFormPost, &m_pLastFormptr,
  802. CURLFORM_COPYNAME, strFieldName.c_str(),
  803. CURLFORM_FILE, strFieldValue.c_str(),
  804. CURLFORM_END);
  805. }
  806. /**
  807. * @brief set the name and the value of an HTML form's input
  808. * (other than "file" like "text", "hidden" or "submit")
  809. *
  810. * @param fieldName name of the input element
  811. * @param fieldValue value to be assigned to the input element
  812. */
  813. void CHTTPClient::PostFormInfo::AddFormContent(const std::string& strFieldName,
  814. const std::string& strFieldValue)
  815. {
  816. curl_formadd(&m_pFormPost, &m_pLastFormptr,
  817. CURLFORM_COPYNAME, strFieldName.c_str(),
  818. CURLFORM_COPYCONTENTS, strFieldValue.c_str(),
  819. CURLFORM_END);
  820. }
  821. // REST REQUESTS
  822. /**
  823. * @brief initializes a REST request
  824. * some common operations to REST requests are performed here,
  825. * the others are performed in Perform method
  826. *
  827. * @param [in] Headers headers to send
  828. * @param [out] Response response data
  829. */
  830. inline const bool CHTTPClient::InitRestRequest(const std::string& strUrl,
  831. const CHTTPClient::HeadersMap& Headers,
  832. CHTTPClient::HttpResponse& Response)
  833. {
  834. if (strUrl.empty())
  835. {
  836. if (m_eSettingsFlags & ENABLE_LOG)
  837. m_oLog(LOG_ERROR_EMPTY_HOST_MSG);
  838. return false;
  839. }
  840. if (!m_pCurlSession)
  841. {
  842. if (m_eSettingsFlags & ENABLE_LOG)
  843. m_oLog(LOG_ERROR_CURL_NOT_INIT_MSG);
  844. return false;
  845. }
  846. // Reset is mandatory to avoid bad surprises
  847. curl_easy_reset(m_pCurlSession);
  848. CheckURL(strUrl);
  849. // set the received body's callback function
  850. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEFUNCTION, &CHTTPClient::RestWriteCallback);
  851. // set data object to pass to callback function above
  852. curl_easy_setopt(m_pCurlSession, CURLOPT_WRITEDATA, &Response);
  853. // set the response's headers processing callback function
  854. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERFUNCTION, &CHTTPClient::RestHeaderCallback);
  855. // callback object for server's responses headers
  856. curl_easy_setopt(m_pCurlSession, CURLOPT_HEADERDATA, &Response);
  857. std::string strHeader;
  858. for (HeadersMap::const_iterator it = Headers.cbegin();
  859. it != Headers.cend();
  860. ++it)
  861. {
  862. strHeader = it->first + ": " + it->second; // build header string
  863. AddHeader(strHeader);
  864. }
  865. return true;
  866. }
  867. /**
  868. * @brief post REST request operations are performed here
  869. *
  870. * @param [in] ePerformCode curl easy perform returned code
  871. * @param [out] Response response data
  872. */
  873. inline const bool CHTTPClient::PostRestRequest(const CURLcode ePerformCode,
  874. CHTTPClient::HttpResponse& Response)
  875. {
  876. // Check for errors
  877. if (ePerformCode != CURLE_OK)
  878. {
  879. Response.strBody.clear();
  880. Response.iCode = -1;
  881. if (m_eSettingsFlags & ENABLE_LOG){
  882. char errMsg[1024] = {0};
  883. _snprintf(errMsg, 1023, LOG_ERROR_CURL_REST_FAILURE_FORMAT, m_strURL.c_str(), ePerformCode,
  884. curl_easy_strerror(ePerformCode));
  885. m_oLog(errMsg);
  886. Response.iCode = ePerformCode;
  887. Response.strBody.append(errMsg);
  888. }
  889. return false;
  890. }
  891. long lHttpCode = 0;
  892. curl_easy_getinfo(m_pCurlSession, CURLINFO_RESPONSE_CODE, &lHttpCode);
  893. Response.iCode = static_cast<int>(lHttpCode);
  894. return true;
  895. }
  896. /**
  897. * @brief performs a HEAD request
  898. *
  899. * @param [in] strUrl url to request
  900. * @param [in] Headers headers to send
  901. * @param [out] Response response data
  902. *
  903. * @retval true Successfully requested the URI.
  904. * @retval false Encountered a problem.
  905. */
  906. const bool CHTTPClient::Head(const std::string& strUrl,
  907. const CHTTPClient::HeadersMap& Headers,
  908. CHTTPClient::HttpResponse& Response)
  909. {
  910. if (InitRestRequest(strUrl, Headers, Response))
  911. {
  912. /** set HTTP HEAD METHOD */
  913. curl_easy_setopt(m_pCurlSession, CURLOPT_CUSTOMREQUEST, "HEAD");
  914. curl_easy_setopt(m_pCurlSession, CURLOPT_NOBODY, 1L);
  915. CURLcode res = Perform();
  916. return PostRestRequest(res, Response);
  917. }
  918. else
  919. return false;
  920. }
  921. /**
  922. * @brief performs a GET request
  923. *
  924. * @param [in] strUrl url to request
  925. * @param [in] Headers headers to send
  926. * @param [out] Response response data
  927. *
  928. * @retval true Successfully requested the URI.
  929. * @retval false Encountered a problem.
  930. */
  931. const bool CHTTPClient::Get(const std::string& strUrl,
  932. const CHTTPClient::HeadersMap& Headers,
  933. CHTTPClient::HttpResponse& Response)
  934. {
  935. if (InitRestRequest(strUrl, Headers, Response))
  936. {
  937. // specify a GET request
  938. curl_easy_setopt(m_pCurlSession, CURLOPT_HTTPGET, 1L);
  939. CURLcode res = Perform();
  940. return PostRestRequest(res, Response);
  941. }
  942. else
  943. return false;
  944. }
  945. /**
  946. * @brief performs a DELETE request
  947. *
  948. * @param [in] strUrl url to request
  949. * @param [in] Headers headers to send
  950. * @param [out] Response response data
  951. *
  952. * @retval true Successfully requested the URI.
  953. * @retval false Encountered a problem.
  954. */
  955. const bool CHTTPClient::Del(const std::string& strUrl,
  956. const CHTTPClient::HeadersMap& Headers,
  957. CHTTPClient::HttpResponse& Response)
  958. {
  959. if (InitRestRequest(strUrl, Headers, Response))
  960. {
  961. curl_easy_setopt(m_pCurlSession, CURLOPT_CUSTOMREQUEST, "DELETE");
  962. CURLcode res = Perform();
  963. return PostRestRequest(res, Response);
  964. }
  965. else
  966. return false;
  967. }
  968. const bool CHTTPClient::Post(const std::string& strUrl,
  969. const CHTTPClient::HeadersMap& Headers,
  970. const std::string& strPostData,
  971. CHTTPClient::HttpResponse& Response)
  972. {
  973. if (InitRestRequest(strUrl, Headers, Response))
  974. {
  975. // specify a POST request
  976. curl_easy_setopt(m_pCurlSession, CURLOPT_POST, 1L);
  977. // set post informations
  978. curl_easy_setopt(m_pCurlSession, CURLOPT_POSTFIELDS, strPostData.c_str());
  979. curl_easy_setopt(m_pCurlSession, CURLOPT_POSTFIELDSIZE, strPostData.size());
  980. CURLcode res = Perform();
  981. return PostRestRequest(res, Response);
  982. }
  983. else
  984. return false;
  985. }
  986. /**
  987. * @brief performs a PUT request with a string
  988. *
  989. * @param [in] strUrl url to request
  990. * @param [in] Headers headers to send
  991. * @param [out] Response response data
  992. *
  993. * @retval true Successfully requested the URI.
  994. * @retval false Encountered a problem.
  995. */
  996. const bool CHTTPClient::Put(const std::string& strUrl, const CHTTPClient::HeadersMap& Headers,
  997. const std::string& strPutData, CHTTPClient::HttpResponse& Response)
  998. {
  999. if (InitRestRequest(strUrl, Headers, Response))
  1000. {
  1001. CHTTPClient::UploadObject Payload;
  1002. Payload.pszData = strPutData.c_str();
  1003. Payload.usLength = strPutData.size();
  1004. // specify a PUT request
  1005. curl_easy_setopt(m_pCurlSession, CURLOPT_PUT, 1L);
  1006. curl_easy_setopt(m_pCurlSession, CURLOPT_UPLOAD, 1L);
  1007. // set read callback function
  1008. curl_easy_setopt(m_pCurlSession, CURLOPT_READFUNCTION, &CHTTPClient::RestReadCallback);
  1009. // set data object to pass to callback function
  1010. curl_easy_setopt(m_pCurlSession, CURLOPT_READDATA, &Payload);
  1011. // set data size
  1012. curl_easy_setopt(m_pCurlSession, CURLOPT_INFILESIZE, static_cast<long>(Payload.usLength));
  1013. CURLcode res = Perform();
  1014. return PostRestRequest(res, Response);
  1015. }
  1016. else
  1017. return false;
  1018. }
  1019. /**
  1020. * @brief performs a PUT request with a byte buffer (vector of char)
  1021. *
  1022. * @param [in] strUrl url to request
  1023. * @param [in] Headers headers to send
  1024. * @param [out] Response response data
  1025. *
  1026. * @retval true Successfully requested the URI.
  1027. * @retval false Encountered a problem.
  1028. */
  1029. const bool CHTTPClient::Put(const std::string& strUrl, const CHTTPClient::HeadersMap& Headers,
  1030. const CHTTPClient::ByteBuffer& Data, CHTTPClient::HttpResponse& Response)
  1031. {
  1032. if (InitRestRequest(strUrl, Headers, Response))
  1033. {
  1034. CHTTPClient::UploadObject Payload;
  1035. Payload.pszData = Data.data();
  1036. Payload.usLength = Data.size();
  1037. // specify a PUT request
  1038. curl_easy_setopt(m_pCurlSession, CURLOPT_PUT, 1L);
  1039. curl_easy_setopt(m_pCurlSession, CURLOPT_UPLOAD, 1L);
  1040. // set read callback function
  1041. curl_easy_setopt(m_pCurlSession, CURLOPT_READFUNCTION, &CHTTPClient::RestReadCallback);
  1042. // set data object to pass to callback function
  1043. curl_easy_setopt(m_pCurlSession, CURLOPT_READDATA, &Payload);
  1044. // set data size
  1045. curl_easy_setopt(m_pCurlSession, CURLOPT_INFILESIZE, static_cast<long>(Payload.usLength));
  1046. CURLcode res = Perform();
  1047. return PostRestRequest(res, Response);
  1048. }
  1049. else
  1050. return false;
  1051. }
  1052. // STRING HELPERS
  1053. /**
  1054. * @brief returns a formatted string
  1055. *
  1056. * @param [in] strFormat string with one or many format specifiers
  1057. * @param [in] parameters to be placed in the format specifiers of strFormat
  1058. *
  1059. * @retval string formatted string
  1060. */
  1061. std::string CHTTPClient::StringFormat(const std::string strFormat, ...)
  1062. {
  1063. int n = (static_cast<int>(strFormat.size())) * 2; // Reserve two times as much as the length of the strFormat
  1064. std::unique_ptr<char[]> pFormatted;
  1065. va_list ap;
  1066. while(true)
  1067. {
  1068. pFormatted.reset(new char[n]); // Wrap the plain char array into the unique_ptr
  1069. strcpy(&pFormatted[0], strFormat.c_str());
  1070. va_start(ap, strFormat);
  1071. int iFinaln = vsnprintf(&pFormatted[0], n, strFormat.c_str(), ap);
  1072. va_end(ap);
  1073. if (iFinaln < 0 || iFinaln >= n)
  1074. {
  1075. n += abs(iFinaln - n + 1);
  1076. }
  1077. else
  1078. {
  1079. break;
  1080. }
  1081. }
  1082. return std::string(pFormatted.get());
  1083. }
  1084. /*std::string CHTTPClient::StringFormat(const std::string strFormat, ...)
  1085. {
  1086. char buffer[1024];
  1087. va_list args;
  1088. va_start(args, strFormat);
  1089. vsnprintf(buffer, 1024, strFormat.c_str(), args);
  1090. va_end (args);
  1091. return std::string(buffer);
  1092. }
  1093. */
  1094. /**
  1095. * @brief removes leading and trailing whitespace from a string
  1096. *
  1097. * @param [in/out] str string to be trimmed
  1098. */
  1099. inline void CHTTPClient::TrimSpaces(std::string& str)
  1100. {
  1101. // trim from left
  1102. str.erase(str.begin(),
  1103. std::find_if(str.begin(), str.end(), [](char c) {return !isspace(c); })
  1104. );
  1105. // trim from right
  1106. str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) {return !isspace(c); }).base(),
  1107. str.end()
  1108. );
  1109. }
  1110. // CURL CALLBACKS
  1111. size_t CHTTPClient::ThrowAwayCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1112. {
  1113. reinterpret_cast<void*>(ptr);
  1114. reinterpret_cast<void*>(data);
  1115. /* we are not interested in the headers itself,
  1116. so we only return the size we would have saved ... */
  1117. return size * nmemb;
  1118. }
  1119. /**
  1120. * @brief stores the server response in a string
  1121. *
  1122. * @param ptr pointer of max size (size*nmemb) to read data from it
  1123. * @param size size parameter
  1124. * @param nmemb memblock parameter
  1125. * @param data pointer to user data (string)
  1126. *
  1127. * @return (size * nmemb)
  1128. */
  1129. size_t CHTTPClient::WriteInStringCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1130. {
  1131. std::string* strWriteHere = reinterpret_cast<std::string*>(data);
  1132. if (strWriteHere != nullptr)
  1133. {
  1134. strWriteHere->append(reinterpret_cast<char*>(ptr), size * nmemb);
  1135. return size * nmemb;
  1136. }
  1137. return 0;
  1138. }
  1139. /**
  1140. * @brief stores the server response in an already opened file stream
  1141. * used by DownloadFile()
  1142. *
  1143. * @param buff pointer of max size (size*nmemb) to read data from it
  1144. * @param size size parameter
  1145. * @param nmemb memblock parameter
  1146. * @param userdata pointer to user data (file stream)
  1147. *
  1148. * @return (size * nmemb)
  1149. */
  1150. size_t CHTTPClient::WriteToFileCallback(void* buff, size_t size, size_t nmemb, void* data)
  1151. {
  1152. if ((size == 0) || (nmemb == 0) || ((size*nmemb) < 1) || (data == nullptr))
  1153. return 0;
  1154. std::ofstream* pFileStream = reinterpret_cast<std::ofstream*>(data);
  1155. if (pFileStream->is_open())
  1156. {
  1157. pFileStream->write(reinterpret_cast<char*>(buff), size * nmemb);
  1158. }
  1159. return size * nmemb;
  1160. }
  1161. /**
  1162. * @brief reads the content of an already opened file stream
  1163. * used by UploadFile()
  1164. *
  1165. * @param ptr pointer of max size (size*nmemb) to write data to it
  1166. * @param size size parameter
  1167. * @param nmemb memblock parameter
  1168. * @param stream pointer to user data (file stream)
  1169. *
  1170. * @return (size * nmemb)
  1171. */
  1172. size_t CHTTPClient::ReadFromFileCallback(void* ptr, size_t size, size_t nmemb, void* stream)
  1173. {
  1174. std::ifstream* pFileStream = reinterpret_cast<std::ifstream*>(stream);
  1175. if (pFileStream->is_open())
  1176. {
  1177. pFileStream->read(reinterpret_cast<char*>(ptr), size * nmemb);
  1178. return pFileStream->gcount();
  1179. }
  1180. return 0;
  1181. }
  1182. // REST CALLBACKS
  1183. /**
  1184. * @brief write callback function for libcurl
  1185. * this callback will be called to store the server's Body reponse
  1186. * in a struct response
  1187. *
  1188. * we can also use an std::vector<char> instead of an std::string but in this case
  1189. * there isn't a big difference... maybe resizing the container with a max size can
  1190. * enhance performances...
  1191. *
  1192. * @param data returned data of size (size*nmemb)
  1193. * @param size size parameter
  1194. * @param nmemb memblock parameter
  1195. * @param userdata pointer to user data to save/work with return data
  1196. *
  1197. * @return (size * nmemb)
  1198. */
  1199. size_t CHTTPClient::RestWriteCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1200. {
  1201. CHTTPClient::HttpResponse* pServerResponse;
  1202. pServerResponse = reinterpret_cast<CHTTPClient::HttpResponse*>(pUserData);
  1203. pServerResponse->strBody.append(reinterpret_cast<char*>(pCurlData), usBlockCount * usBlockSize);
  1204. return (usBlockCount * usBlockSize);
  1205. }
  1206. /**
  1207. * @brief header callback for libcurl
  1208. * callback used to process response's headers (received)
  1209. *
  1210. * @param data returned (header line)
  1211. * @param size of data
  1212. * @param nmemb memblock
  1213. * @param userdata pointer to user data object to save header data
  1214. * @return size * nmemb;
  1215. */
  1216. size_t CHTTPClient::RestHeaderCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1217. {
  1218. CHTTPClient::HttpResponse* pServerResponse;
  1219. pServerResponse = reinterpret_cast<CHTTPClient::HttpResponse*>(pUserData);
  1220. std::string strHeader(reinterpret_cast<char*>(pCurlData), usBlockCount * usBlockSize);
  1221. size_t usSeperator = strHeader.find_first_of(":");
  1222. if (std::string::npos == usSeperator)
  1223. {
  1224. //roll with non seperated headers or response's line
  1225. TrimSpaces(strHeader);
  1226. if (0 == strHeader.length())
  1227. {
  1228. return (usBlockCount * usBlockSize); //blank line;
  1229. }
  1230. pServerResponse->mapHeaders[strHeader] = "present";
  1231. }
  1232. else
  1233. {
  1234. std::string strKey = strHeader.substr(0, usSeperator);
  1235. TrimSpaces(strKey);
  1236. std::string strValue = strHeader.substr(usSeperator + 1);
  1237. TrimSpaces(strValue);
  1238. pServerResponse->mapHeaders[strKey] = strValue;
  1239. }
  1240. return (usBlockCount * usBlockSize);
  1241. }
  1242. size_t CHTTPClient::HeaderCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1243. {
  1244. CHTTPClient::HeadersMap *pheaderMap;
  1245. pheaderMap = reinterpret_cast<CHTTPClient::HeadersMap*>(pUserData);
  1246. std::string strHeader(reinterpret_cast<char*>(pCurlData), usBlockCount * usBlockSize);
  1247. size_t usSeperator = strHeader.find_first_of(":");
  1248. if (std::string::npos == usSeperator)
  1249. {
  1250. //roll with non seperated headers or response's line
  1251. TrimSpaces(strHeader);
  1252. if (0 == strHeader.length())
  1253. {
  1254. return (usBlockCount * usBlockSize); //blank line;
  1255. }
  1256. (*pheaderMap)[strHeader] = "present";
  1257. }
  1258. else
  1259. {
  1260. std::string strKey = strHeader.substr(0, usSeperator);
  1261. TrimSpaces(strKey);
  1262. std::string strValue = strHeader.substr(usSeperator + 1);
  1263. TrimSpaces(strValue);
  1264. (*pheaderMap)[strKey] = strValue;
  1265. }
  1266. return (usBlockCount * usBlockSize);
  1267. }
  1268. size_t CHTTPClient:: WriteInByteCallback(void* ptr, size_t size, size_t nmemb, void* pUserData)
  1269. {
  1270. fileContentArray *wbyte = reinterpret_cast<fileContentArray*>(pUserData);
  1271. if (wbyte == NULL || wbyte->copyPtr == NULL) {
  1272. return -1;
  1273. }
  1274. else {
  1275. size_t len = size * nmemb;
  1276. *(wbyte->curLen) += len;
  1277. if (len != 0 && *(wbyte->curLen) <= wbyte->maxLen) {
  1278. memcpy(wbyte->copyPtr, ptr, len);
  1279. wbyte->copyPtr += len;//移动指针
  1280. return len;
  1281. }
  1282. else {
  1283. return -2;
  1284. }
  1285. }
  1286. }
  1287. /**
  1288. * @brief read callback function for libcurl
  1289. * used to send (or upload) a content to the server
  1290. *
  1291. * @param pointer of max size (size*nmemb) to write data to (used by cURL to send data)
  1292. * @param size size parameter
  1293. * @param nmemb memblock parameter
  1294. * @param userdata pointer to user data to read data from
  1295. *
  1296. * @return (size * nmemb)
  1297. */
  1298. size_t CHTTPClient::RestReadCallback(void* pCurlData, size_t usBlockCount, size_t usBlockSize, void* pUserData)
  1299. {
  1300. // get upload struct
  1301. CHTTPClient::UploadObject* Payload;
  1302. Payload = reinterpret_cast<CHTTPClient::UploadObject*>(pUserData);
  1303. // set correct sizes
  1304. size_t usCurlSize = usBlockCount * usBlockSize;
  1305. size_t usCopySize = (Payload->usLength < usCurlSize) ? Payload->usLength : usCurlSize;
  1306. /** copy data to buffer */
  1307. std::memcpy(pCurlData, Payload->pszData, usCopySize);
  1308. // decrement length and increment data pointer
  1309. Payload->usLength -= usCopySize; // remaining bytes to be sent
  1310. Payload->pszData += usCopySize; // next byte to the chunk that will be sent
  1311. /** return copied size */
  1312. return usCopySize;
  1313. }
  1314. //add by cfq
  1315. const bool CHTTPClient::Get(CHTTPReq &req, CHTTPRet &ret, HttpClientTraceLink* pTrace){
  1316. //拼接请求参数
  1317. string param;
  1318. std::string jsonStr="";
  1319. try
  1320. {
  1321. jsonStr= req.ToJson();
  1322. }
  1323. catch (...)
  1324. {
  1325. m_oLog(LOG_ERROR_GET_JSON_FAILTURE_MSG);
  1326. }
  1327. if(jsonStr.empty())
  1328. {
  1329. param = "";
  1330. }
  1331. else
  1332. {
  1333. Json::Value root;
  1334. Json::Reader reader;
  1335. reader.parse(jsonStr,root,false);
  1336. Json::Value::Members mem = root.getMemberNames();
  1337. for(auto iter = mem.begin(); iter != mem.end(); iter++){
  1338. switch(root[*iter].type()){
  1339. case Json::intValue:
  1340. char a[20];
  1341. _snprintf(a, sizeof(a), "%d", root[*iter].asInt());
  1342. param = param.append((*iter).c_str()).append("=").append(a);
  1343. break;
  1344. case Json::stringValue:
  1345. param = param.append((*iter).c_str()).append("=").append(root[*iter].asCString());
  1346. break;
  1347. case Json::realValue:
  1348. char b[20];
  1349. _snprintf(b, sizeof(b), "%.21f", root[*iter].asDouble());
  1350. param = param.append((*iter).c_str()).append("=").append(b);
  1351. break;
  1352. case Json::booleanValue:
  1353. param = param.append((*iter).c_str()).append("=").append(root[*iter].asBool() ? "true": "false");
  1354. break;
  1355. default:
  1356. break;
  1357. }
  1358. if((iter + 1) != mem.end()){
  1359. param = param.append("&");
  1360. }
  1361. //root.clear();
  1362. }
  1363. }
  1364. char requestData[20000];
  1365. _snprintf(requestData, sizeof(requestData), "%s", param.c_str());
  1366. if(req.m_printDbg){
  1367. m_oLog(requestData);
  1368. }
  1369. //urlEncode
  1370. char *requestData_encode = curl_easy_escape(m_pCurlSession, requestData, 0);
  1371. if(req.m_printDbg){
  1372. string str;
  1373. str.append("queryString encode:");
  1374. str.append(requestData);
  1375. m_oLog(str.c_str());
  1376. }
  1377. if(!req.m_url.empty()){
  1378. char *url = new char[req.m_url.length()+param.length()+2];
  1379. _snprintf(url, req.m_url.length()+param.length()+1, "%s?%s", req.m_url.c_str(), param.c_str());
  1380. m_oLog(url);
  1381. delete[] url;
  1382. }
  1383. else{
  1384. m_oLog(LOG_ERROR_PATH_NULL_MSG);
  1385. return false;
  1386. }
  1387. if(req.m_headers.empty()){
  1388. if(req.m_printDbg){
  1389. m_oLog("没有指定请求头内容,使用默认值Accept=application/json");
  1390. }
  1391. req.m_headers.emplace(std::make_pair("Accept", "application/json"));
  1392. }
  1393. if (req.m_withToken && g_tokenCall != NULL)
  1394. {
  1395. std::string channelId = "";
  1396. std::string token = "";
  1397. std::string terminalno = "";
  1398. std::string reserve1 = "";
  1399. g_tokenCall(channelId, token, terminalno, reserve1);
  1400. if (channelId.length() != 0 && token.length() != 0)
  1401. {
  1402. req.m_headers.emplace(std::make_pair("channelId", channelId));
  1403. req.m_headers.emplace(std::make_pair("token", token));
  1404. req.m_headers.emplace(std::make_pair("terminalno", terminalno));
  1405. string out = "channelId:" + channelId + ", token:" + token;
  1406. if (req.m_printDbg)
  1407. m_oLog(out.c_str());
  1408. }
  1409. }
  1410. if (pTrace != NULL
  1411. && strlen(pTrace->X_B3_BusinessId) > 0
  1412. && strlen(pTrace->X_B3_TraceId) > 0
  1413. && strlen(pTrace->X_B3_SpanId) > 0
  1414. && strlen(pTrace->X_B3_ParentSpanId) > 0
  1415. && strlen(pTrace->X_B3_Timestamp) > 0)
  1416. {
  1417. req.m_headers.emplace(std::make_pair("X_B3_BusinessId", pTrace->X_B3_BusinessId));
  1418. req.m_headers.emplace(std::make_pair("X_B3_TraceId", pTrace->X_B3_TraceId));
  1419. req.m_headers.emplace(std::make_pair("X_B3_SpanId", pTrace->X_B3_SpanId));
  1420. req.m_headers.emplace(std::make_pair("X_B3_ParentSpanId", pTrace->X_B3_ParentSpanId));
  1421. req.m_headers.emplace(std::make_pair("X_B3_Timestamp", pTrace->X_B3_Timestamp));
  1422. }
  1423. //set timeout
  1424. m_iCurlTimeout = req.m_timeOut;
  1425. CHTTPClient::HttpResponse g_Response;
  1426. string url = req.m_url + "?" + param;
  1427. if(req.m_bTransCode){
  1428. if(req.m_printDbg)
  1429. m_oLog("url转码 GBK=>UTF-8");
  1430. ConvertGBKToUtf8(url);
  1431. }
  1432. bool isSuccess = Get(url, req.m_headers, g_Response);
  1433. //转码
  1434. if(req.m_bTransCode){
  1435. if(req.m_printDbg)
  1436. m_oLog("responseData转码 UTF-8=>GBK");
  1437. ConvertUtf8ToGBK(g_Response.strBody);
  1438. }
  1439. if(req.m_printDbg){
  1440. std::string msg = "是否是https请求:";
  1441. msg.append(m_bHTTPS ? "true" : "false");
  1442. m_oLog(msg.c_str());
  1443. }
  1444. //处理响应值
  1445. ret.m_sysCode = g_Response.iCode;
  1446. ret.m_resultData = g_Response.strBody;
  1447. if(isSuccess == false || (g_Response.iCode != 200 && g_Response.iCode != 201)){
  1448. ret.m_errMsg = g_Response.strBody;
  1449. char errMsg[1024] = {0};
  1450. _snprintf(errMsg, 1023, "http请求报错,错误码:%d", g_Response.iCode);
  1451. m_oLog(errMsg);
  1452. return false;
  1453. }
  1454. else
  1455. {
  1456. if(req.m_printDbg)
  1457. m_oLog("http请求成功,开始解析json");
  1458. try
  1459. {
  1460. Json::Value root;
  1461. Json::Reader reader;
  1462. reader.parse(g_Response.strBody,root,false);
  1463. if(root.isMember("code") && root.isMember("message"))
  1464. {
  1465. ret.m_userCode = root["code"].asString();
  1466. ret.m_errMsg = root["message"].asString();
  1467. return ret.Parse(g_Response.strBody);
  1468. }
  1469. else
  1470. {
  1471. char errMsg[1024] = {0};
  1472. _snprintf(errMsg, 1023, LOG_ERROR_RESPONSE_FORMAT_FAILTURE_MSG, g_Response.strBody.c_str());
  1473. ret.m_userCode = "0";
  1474. ret.m_errMsg = "Unexpected format of stupid previous assuption!";
  1475. return true;
  1476. }
  1477. }
  1478. catch(...){
  1479. m_oLog(LOG_ERROR_PARSE_JSON_FAILTURE_MSG);
  1480. return false;
  1481. }
  1482. }
  1483. }
  1484. //add by cfq
  1485. const bool CHTTPClient::Post(CHTTPReq &req, CHTTPRet &ret, HttpClientTraceLink* pTrace){
  1486. if(!req.m_url.empty()){
  1487. if(req.m_printDbg){
  1488. char *url = new char[req.m_url.length() + 1];
  1489. memset(url, 0, req.m_url.length() + 1);
  1490. _snprintf(url, req.m_url.length(), "%s", req.m_url.c_str());
  1491. m_oLog(url);
  1492. delete[] url;
  1493. }
  1494. }
  1495. else{
  1496. m_oLog(LOG_ERROR_PATH_NULL_MSG);
  1497. return false;
  1498. }
  1499. std::string request;
  1500. try
  1501. {
  1502. request= req.ToJson();
  1503. }
  1504. catch (...)
  1505. {
  1506. m_oLog(LOG_ERROR_GET_JSON_FAILTURE_MSG);
  1507. }
  1508. //转码
  1509. if(req.m_bTransCode){
  1510. if(req.m_printDbg){
  1511. m_oLog("url转码 GBK=>UTF-8");
  1512. }
  1513. ConvertGBKToUtf8(request);
  1514. }
  1515. if(req.m_printDbg){
  1516. std:string msg = "strPostDate:";
  1517. msg.append(request);
  1518. m_oLog(msg.c_str());
  1519. }
  1520. if(req.m_headers.empty()){
  1521. if(req.m_printDbg){
  1522. m_oLog("没有指定请求头内容,使用默认值Content-Type=application/json");
  1523. }
  1524. req.m_headers.emplace(std::make_pair("Content-Type", "application/json"));
  1525. }
  1526. if (req.m_withToken && g_tokenCall != NULL)
  1527. {
  1528. std::string channelId = "";
  1529. std::string token = "";
  1530. std::string terminalno = "";
  1531. std::string reserve1 = "";
  1532. g_tokenCall(channelId, token, terminalno, reserve1);
  1533. if (channelId.length() != 0 && token.length() != 0)
  1534. {
  1535. req.m_headers.emplace(std::make_pair("channelId", channelId));
  1536. req.m_headers.emplace(std::make_pair("token", token));
  1537. req.m_headers.emplace(std::make_pair("terminalno", terminalno));
  1538. string out = "channelId:" + channelId + ", token:" + token;
  1539. if (req.m_printDbg)
  1540. m_oLog(out.c_str());
  1541. }
  1542. }
  1543. if (pTrace != NULL
  1544. && strlen(pTrace->X_B3_BusinessId) > 0
  1545. && strlen(pTrace->X_B3_TraceId) > 0
  1546. && strlen(pTrace->X_B3_SpanId) > 0
  1547. && strlen(pTrace->X_B3_ParentSpanId) > 0
  1548. && strlen(pTrace->X_B3_Timestamp) > 0)
  1549. {
  1550. req.m_headers.emplace(std::make_pair("X_B3_BusinessId", pTrace->X_B3_BusinessId));
  1551. req.m_headers.emplace(std::make_pair("X_B3_TraceId", pTrace->X_B3_TraceId));
  1552. req.m_headers.emplace(std::make_pair("X_B3_SpanId", pTrace->X_B3_SpanId));
  1553. req.m_headers.emplace(std::make_pair("X_B3_ParentSpanId", pTrace->X_B3_ParentSpanId));
  1554. req.m_headers.emplace(std::make_pair("X_B3_Timestamp", pTrace->X_B3_Timestamp));
  1555. }
  1556. //set timeout
  1557. m_iCurlTimeout = req.m_timeOut;
  1558. CHTTPClient::HttpResponse g_Response;
  1559. bool isSuccess = Post(req.m_url, req.m_headers, request, g_Response);
  1560. //转码
  1561. if(req.m_bTransCode){
  1562. if(req.m_printDbg){
  1563. m_oLog("url转码 GBK=>UTF-8");
  1564. }
  1565. ConvertUtf8ToGBK(g_Response.strBody);
  1566. }
  1567. if(req.m_printDbg){
  1568. std::string msg = "是否是https请求:";
  1569. msg.append(m_bHTTPS ? "true" : "false");
  1570. m_oLog(msg.c_str());
  1571. }
  1572. //处理响应值
  1573. ret.m_sysCode = g_Response.iCode;
  1574. ret.m_resultData = g_Response.strBody;
  1575. if(isSuccess == false || (g_Response.iCode != 200 && g_Response.iCode != 201)){
  1576. ret.m_errMsg = g_Response.strBody;
  1577. char errMsg[1024] = {0};
  1578. _snprintf(errMsg, 1023, "http请求报错,错误码:%d", g_Response.iCode);
  1579. m_oLog(errMsg);
  1580. return false;
  1581. }
  1582. else
  1583. {
  1584. if(req.m_printDbg){
  1585. m_oLog("http请求成功,开始解析json");
  1586. }
  1587. try
  1588. {
  1589. Json::Value root;
  1590. Json::Reader reader;
  1591. reader.parse(g_Response.strBody,root,false);
  1592. if(root.isMember("code") && root.isMember("message"))
  1593. {
  1594. ret.m_userCode = root["code"].asString();
  1595. ret.m_errMsg = root["message"].asString();
  1596. return ret.Parse(g_Response.strBody);
  1597. }
  1598. else
  1599. {
  1600. char errMsg[1024] = {0};
  1601. _snprintf(errMsg, 1023, LOG_ERROR_RESPONSE_FORMAT_FAILTURE_MSG, g_Response.strBody.c_str());
  1602. ret.m_userCode = "0";
  1603. ret.m_errMsg = "Unexpected format of stupid previous assuption!";
  1604. return true;
  1605. }
  1606. }
  1607. catch(...){
  1608. m_oLog(LOG_ERROR_PARSE_JSON_FAILTURE_MSG);
  1609. return false;
  1610. }
  1611. }
  1612. }
  1613. // CURL DEBUG INFO CALLBACKS
  1614. #ifdef DEBUG_CURL
  1615. void CHTTPClient::SetCurlTraceLogDirectory(const std::string& strPath)
  1616. {
  1617. s_strCurlTraceLogDirectory = strPath;
  1618. if (!s_strCurlTraceLogDirectory.empty()
  1619. #ifdef WINDOWS
  1620. && s_strCurlTraceLogDirectory.at(s_strCurlTraceLogDirectory.length() - 1) != '\\')
  1621. {
  1622. s_strCurlTraceLogDirectory += '\\';
  1623. }
  1624. #else
  1625. && s_strCurlTraceLogDirectory.at(s_strCurlTraceLogDirectory.length() - 1) != '/')
  1626. {
  1627. s_strCurlTraceLogDirectory += '/';
  1628. }
  1629. #endif
  1630. }
  1631. int CHTTPClient::DebugCallback(CURL* curl, curl_infotype curl_info_type, char* pszTrace, size_t usSize, void* pFile)
  1632. {
  1633. std::string strText;
  1634. std::string strTrace(pszTrace, usSize);
  1635. switch (curl_info_type)
  1636. {
  1637. case CURLINFO_TEXT:
  1638. strText = "# Information : ";
  1639. break;
  1640. case CURLINFO_HEADER_OUT:
  1641. strText = "-> Sending header : ";
  1642. break;
  1643. case CURLINFO_DATA_OUT:
  1644. strText = "-> Sending data : ";
  1645. break;
  1646. case CURLINFO_SSL_DATA_OUT:
  1647. strText = "-> Sending SSL data : ";
  1648. break;
  1649. case CURLINFO_HEADER_IN:
  1650. strText = "<- Receiving header : ";
  1651. break;
  1652. case CURLINFO_DATA_IN:
  1653. strText = "<- Receiving unencrypted data : ";
  1654. break;
  1655. case CURLINFO_SSL_DATA_IN:
  1656. strText = "<- Receiving SSL data : ";
  1657. break;
  1658. default:
  1659. break;
  1660. }
  1661. std::ofstream* pofTraceFile = reinterpret_cast<std::ofstream*>(pFile);
  1662. if (pofTraceFile == nullptr)
  1663. {
  1664. std::cout << "[DEBUG] cURL debug log [" << curl_info_type << "]: " << " - " << strTrace;
  1665. }
  1666. else
  1667. {
  1668. (*pofTraceFile) << strText << strTrace;
  1669. }
  1670. return 0;
  1671. }
  1672. void CHTTPClient::StartCurlDebug() const
  1673. {
  1674. if (!m_ofFileCurlTrace.is_open())
  1675. {
  1676. curl_easy_setopt(m_pCurlSession, CURLOPT_VERBOSE, 1L);
  1677. curl_easy_setopt(m_pCurlSession, CURLOPT_DEBUGFUNCTION, DebugCallback);
  1678. std::string strFileCurlTraceFullName(s_strCurlTraceLogDirectory);
  1679. if (!strFileCurlTraceFullName.empty())
  1680. {
  1681. char szDate[32];
  1682. memset(szDate, 0, 32);
  1683. time_t tNow; time(&tNow);
  1684. // new trace file for each hour
  1685. strftime(szDate, 32, "%Y%m%d_%H", localtime(&tNow));
  1686. strFileCurlTraceFullName += "TraceLog_";
  1687. strFileCurlTraceFullName += szDate;
  1688. strFileCurlTraceFullName += ".txt";
  1689. m_ofFileCurlTrace.open(strFileCurlTraceFullName, std::ifstream::app | std::ifstream::binary);
  1690. if (m_ofFileCurlTrace)
  1691. curl_easy_setopt(m_pCurlSession, CURLOPT_DEBUGDATA, &m_ofFileCurlTrace);
  1692. }
  1693. }
  1694. }
  1695. void CHTTPClient::EndCurlDebug() const
  1696. {
  1697. if (m_ofFileCurlTrace && m_ofFileCurlTrace.is_open())
  1698. {
  1699. m_ofFileCurlTrace << "###########################################" << std::endl;
  1700. m_ofFileCurlTrace.close();
  1701. }
  1702. }
  1703. #endif