HttpClient-android.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. /****************************************************************************
  2. Copyright (c) 2012 greathqy
  3. Copyright (c) 2012 cocos2d-x.org
  4. Copyright (c) 2013-2016 Chukong Technologies Inc.
  5. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "platform/CCPlatformConfig.h"
  24. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  25. #include "network/HttpClient.h"
  26. #include <queue>
  27. #include <sstream>
  28. #include <stdio.h>
  29. #include <errno.h>
  30. #include "base/CCDirector.h"
  31. #include "platform/CCFileUtils.h"
  32. #include "platform/android/jni/JniHelper.h"
  33. #include "base/ccUTF8.h"
  34. NS_CC_BEGIN
  35. namespace network {
  36. typedef std::vector<std::string> HttpRequestHeaders;
  37. typedef HttpRequestHeaders::iterator HttpRequestHeadersIter;
  38. typedef std::vector<std::string> HttpCookies;
  39. typedef HttpCookies::iterator HttpCookiesIter;
  40. static HttpClient* _httpClient = nullptr; // pointer to singleton
  41. struct CookiesInfo
  42. {
  43. std::string domain;
  44. bool tailmatch;
  45. std::string path;
  46. bool secure;
  47. std::string key;
  48. std::string value;
  49. std::string expires;
  50. };
  51. //static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream)
  52. static size_t writeData(void* buffer, size_t sizes, HttpResponse* response)
  53. {
  54. std::vector<char> * recvBuffer = (std::vector<char>*)response->getResponseData();
  55. recvBuffer->clear();
  56. recvBuffer->insert(recvBuffer->end(), (char*)buffer, ((char*)buffer) + sizes);
  57. return sizes;
  58. }
  59. //static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream)
  60. size_t writeHeaderData(void* buffer, size_t sizes,HttpResponse* response)
  61. {
  62. std::vector<char> * recvBuffer = (std::vector<char>*) response->getResponseHeader();
  63. recvBuffer->clear();
  64. recvBuffer->insert(recvBuffer->end(), (char*)buffer, (char*)buffer + sizes);
  65. return sizes;
  66. }
  67. class HttpURLConnection
  68. {
  69. public:
  70. HttpURLConnection(HttpClient* httpClient)
  71. :_client(httpClient)
  72. ,_httpURLConnection(nullptr)
  73. ,_requestmethod("")
  74. ,_responseCookies("")
  75. ,_cookieFileName("")
  76. ,_contentLength(0)
  77. {
  78. }
  79. ~HttpURLConnection()
  80. {
  81. if(_httpURLConnection != nullptr)
  82. {
  83. JniHelper::getEnv()->DeleteGlobalRef(_httpURLConnection);
  84. }
  85. }
  86. void setRequestMethod(const char* method)
  87. {
  88. _requestmethod = method;
  89. JniMethodInfo methodInfo;
  90. if (JniHelper::getStaticMethodInfo(methodInfo,
  91. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  92. "setRequestMethod",
  93. "(Ljava/net/HttpURLConnection;Ljava/lang/String;)V"))
  94. {
  95. jstring jstr = methodInfo.env->NewStringUTF(_requestmethod.c_str());
  96. methodInfo.env->CallStaticVoidMethod(
  97. methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstr);
  98. methodInfo.env->DeleteLocalRef(jstr);
  99. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  100. }
  101. }
  102. bool init(HttpRequest* request)
  103. {
  104. createHttpURLConnection(request->getUrl());
  105. if(!configure())
  106. {
  107. return false;
  108. }
  109. /* get custom header data (if set) */
  110. HttpRequestHeaders headers=request->getHeaders();
  111. if(!headers.empty())
  112. {
  113. /* append custom headers one by one */
  114. for (auto& header : headers)
  115. {
  116. int len = header.length();
  117. int pos = header.find(':');
  118. if (-1 == pos || pos >= len)
  119. {
  120. continue;
  121. }
  122. std::string str1 = header.substr(0, pos);
  123. std::string str2 = header.substr(pos + 1, len - pos - 1);
  124. addRequestHeader(str1.c_str(), str2.c_str());
  125. }
  126. }
  127. addCookiesForRequestHeader();
  128. return true;
  129. }
  130. int connect()
  131. {
  132. int suc = 0;
  133. JniMethodInfo methodInfo;
  134. if (JniHelper::getStaticMethodInfo(methodInfo,
  135. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  136. "connect",
  137. "(Ljava/net/HttpURLConnection;)I"))
  138. {
  139. suc = methodInfo.env->CallStaticIntMethod(
  140. methodInfo.classID, methodInfo.methodID, _httpURLConnection);
  141. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  142. }
  143. return suc;
  144. }
  145. void disconnect()
  146. {
  147. JniMethodInfo methodInfo;
  148. if (JniHelper::getStaticMethodInfo(methodInfo,
  149. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  150. "disconnect",
  151. "(Ljava/net/HttpURLConnection;)V"))
  152. {
  153. methodInfo.env->CallStaticVoidMethod(
  154. methodInfo.classID, methodInfo.methodID, _httpURLConnection);
  155. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  156. }
  157. }
  158. int getResponseCode()
  159. {
  160. int responseCode = 0;
  161. JniMethodInfo methodInfo;
  162. if (JniHelper::getStaticMethodInfo(methodInfo,
  163. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  164. "getResponseCode",
  165. "(Ljava/net/HttpURLConnection;)I"))
  166. {
  167. responseCode = methodInfo.env->CallStaticIntMethod(
  168. methodInfo.classID, methodInfo.methodID, _httpURLConnection);
  169. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  170. }
  171. return responseCode;
  172. }
  173. char* getResponseMessage()
  174. {
  175. char* message = nullptr;
  176. JniMethodInfo methodInfo;
  177. if (JniHelper::getStaticMethodInfo(methodInfo,
  178. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  179. "getResponseMessage",
  180. "(Ljava/net/HttpURLConnection;)Ljava/lang/String;"))
  181. {
  182. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  183. methodInfo.classID, methodInfo.methodID, _httpURLConnection);
  184. message = getBufferFromJString((jstring)jObj, methodInfo.env);
  185. if (nullptr != jObj)
  186. {
  187. methodInfo.env->DeleteLocalRef(jObj);
  188. }
  189. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  190. }
  191. return message;
  192. }
  193. void sendRequest(HttpRequest* request)
  194. {
  195. JniMethodInfo methodInfo;
  196. if (JniHelper::getStaticMethodInfo(methodInfo,
  197. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  198. "sendRequest",
  199. "(Ljava/net/HttpURLConnection;[B)V"))
  200. {
  201. jbyteArray bytearray;
  202. ssize_t dataSize = request->getRequestDataSize();
  203. bytearray = methodInfo.env->NewByteArray(dataSize);
  204. methodInfo.env->SetByteArrayRegion(bytearray, 0, dataSize, (const jbyte*)request->getRequestData());
  205. methodInfo.env->CallStaticVoidMethod(
  206. methodInfo.classID, methodInfo.methodID, _httpURLConnection, bytearray);
  207. methodInfo.env->DeleteLocalRef(bytearray);
  208. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  209. }
  210. }
  211. size_t saveResponseCookies(const char* responseCookies, size_t count)
  212. {
  213. if (nullptr == responseCookies || strlen(responseCookies) == 0 || count == 0)
  214. {
  215. return 0;
  216. }
  217. if (_cookieFileName.empty())
  218. {
  219. _cookieFileName = FileUtils::getInstance()->getWritablePath() + "cookieFile.txt";
  220. }
  221. FILE* fp = fopen(_cookieFileName.c_str(), "w");
  222. if (nullptr == fp)
  223. {
  224. CCLOG("can't create or open response cookie files");
  225. return 0;
  226. }
  227. fwrite(responseCookies, sizeof(char), count, fp);
  228. fclose(fp);
  229. return count;
  230. }
  231. char* getResponseHeaders()
  232. {
  233. char* headers = nullptr;
  234. JniMethodInfo methodInfo;
  235. if (JniHelper::getStaticMethodInfo(methodInfo,
  236. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  237. "getResponseHeaders",
  238. "(Ljava/net/HttpURLConnection;)Ljava/lang/String;"))
  239. {
  240. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  241. methodInfo.classID, methodInfo.methodID, _httpURLConnection);
  242. headers = getBufferFromJString((jstring)jObj, methodInfo.env);
  243. if (nullptr != jObj) {
  244. methodInfo.env->DeleteLocalRef(jObj);
  245. }
  246. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  247. }
  248. return headers;
  249. }
  250. char* getResponseContent(HttpResponse* response)
  251. {
  252. if (nullptr == response)
  253. {
  254. return nullptr;
  255. }
  256. char* content = nullptr;
  257. JniMethodInfo methodInfo;
  258. if (JniHelper::getStaticMethodInfo(methodInfo,
  259. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  260. "getResponseContent",
  261. "(Ljava/net/HttpURLConnection;)[B"))
  262. {
  263. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  264. methodInfo.classID, methodInfo.methodID, _httpURLConnection);
  265. _contentLength = getCStrFromJByteArray((jbyteArray)jObj, methodInfo.env, &content);
  266. if (nullptr != jObj)
  267. {
  268. methodInfo.env->DeleteLocalRef(jObj);
  269. }
  270. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  271. }
  272. return content;
  273. }
  274. char* getResponseHeaderByKey(const char* key)
  275. {
  276. char* value = nullptr;
  277. JniMethodInfo methodInfo;
  278. if (JniHelper::getStaticMethodInfo(methodInfo,
  279. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  280. "getResponseHeaderByKey",
  281. "(Ljava/net/HttpURLConnection;Ljava/lang/String;)Ljava/lang/String;"))
  282. {
  283. jstring jstrKey = methodInfo.env->NewStringUTF(key);
  284. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  285. methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey);
  286. value = getBufferFromJString((jstring)jObj, methodInfo.env);
  287. methodInfo.env->DeleteLocalRef(jstrKey);
  288. if (nullptr != jObj) {
  289. methodInfo.env->DeleteLocalRef(jObj);
  290. }
  291. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  292. }
  293. return value;
  294. }
  295. int getResponseHeaderByKeyInt(const char* key)
  296. {
  297. int contentLength = 0;
  298. JniMethodInfo methodInfo;
  299. if (JniHelper::getStaticMethodInfo(methodInfo,
  300. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  301. "getResponseHeaderByKeyInt",
  302. "(Ljava/net/HttpURLConnection;Ljava/lang/String;)I"))
  303. {
  304. jstring jstrKey = methodInfo.env->NewStringUTF(key);
  305. contentLength = methodInfo.env->CallStaticIntMethod(
  306. methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey);
  307. methodInfo.env->DeleteLocalRef(jstrKey);
  308. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  309. }
  310. return contentLength;
  311. }
  312. char* getResponseHeaderByIdx(int idx)
  313. {
  314. char* header = nullptr;
  315. JniMethodInfo methodInfo;
  316. if (JniHelper::getStaticMethodInfo(methodInfo,
  317. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  318. "getResponseHeaderByIdx",
  319. "(Ljava/net/HttpURLConnection;I)Ljava/lang/String;"))
  320. {
  321. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  322. methodInfo.classID, methodInfo.methodID, _httpURLConnection, idx);
  323. header = getBufferFromJString((jstring)jObj, methodInfo.env);
  324. if (nullptr != jObj) {
  325. methodInfo.env->DeleteLocalRef(jObj);
  326. }
  327. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  328. }
  329. return header;
  330. }
  331. const std::string& getCookieFileName() const
  332. {
  333. return _cookieFileName;
  334. }
  335. void setCookieFileName(std::string& filename)
  336. {
  337. _cookieFileName = filename;
  338. }
  339. int getContentLength()
  340. {
  341. return _contentLength;
  342. }
  343. private:
  344. void createHttpURLConnection(const std::string& url)
  345. {
  346. JniMethodInfo methodInfo;
  347. if (JniHelper::getStaticMethodInfo(methodInfo,
  348. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  349. "createHttpURLConnection",
  350. "(Ljava/lang/String;)Ljava/net/HttpURLConnection;"))
  351. {
  352. _url = url;
  353. jstring jurl = methodInfo.env->NewStringUTF(url.c_str());
  354. jobject jObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, jurl);
  355. _httpURLConnection = methodInfo.env->NewGlobalRef(jObj);
  356. methodInfo.env->DeleteLocalRef(jurl);
  357. methodInfo.env->DeleteLocalRef(jObj);
  358. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  359. }
  360. }
  361. void addRequestHeader(const char* key, const char* value)
  362. {
  363. JniMethodInfo methodInfo;
  364. if (JniHelper::getStaticMethodInfo(methodInfo,
  365. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  366. "addRequestHeader",
  367. "(Ljava/net/HttpURLConnection;Ljava/lang/String;Ljava/lang/String;)V"))
  368. {
  369. jstring jstrKey = methodInfo.env->NewStringUTF(key);
  370. jstring jstrVal = methodInfo.env->NewStringUTF(value);
  371. methodInfo.env->CallStaticVoidMethod(
  372. methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey, jstrVal);
  373. methodInfo.env->DeleteLocalRef(jstrKey);
  374. methodInfo.env->DeleteLocalRef(jstrVal);
  375. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  376. }
  377. }
  378. void addCookiesForRequestHeader()
  379. {
  380. if(_client->getCookieFilename().empty())
  381. {
  382. return;
  383. }
  384. _cookieFileName = FileUtils::getInstance()->fullPathForFilename(_client->getCookieFilename());
  385. std::string cookiesInfo = FileUtils::getInstance()->getStringFromFile(_cookieFileName);
  386. if (cookiesInfo.empty())
  387. return;
  388. HttpCookies cookiesVec;
  389. cookiesVec.clear();
  390. std::stringstream stream(cookiesInfo);
  391. std::string item;
  392. while (std::getline(stream, item, '\n'))
  393. {
  394. cookiesVec.push_back(item);
  395. }
  396. if (cookiesVec.empty())
  397. return;
  398. std::vector<CookiesInfo> cookiesInfoVec;
  399. cookiesInfoVec.clear();
  400. for (auto& cookies : cookiesVec)
  401. {
  402. if (cookies.find("#HttpOnly_") != std::string::npos)
  403. {
  404. cookies = cookies.substr(10);
  405. }
  406. if(cookies.at(0) == '#')
  407. continue;
  408. CookiesInfo co;
  409. std::stringstream streamInfo(cookies);
  410. std::string item;
  411. std::vector<std::string> elems;
  412. while (std::getline(streamInfo, item, '\t'))
  413. {
  414. elems.push_back(item);
  415. }
  416. co.domain = elems[0];
  417. if (co.domain.at(0) == '.')
  418. {
  419. co.domain = co.domain.substr(1);
  420. }
  421. co.tailmatch = strcmp("TRUE", elems.at(1).c_str())?true: false;
  422. co.path = elems.at(2);
  423. co.secure = strcmp("TRUE", elems.at(3).c_str())?true: false;
  424. co.expires = elems.at(4);
  425. co.key = elems.at(5);
  426. co.value = elems.at(6);
  427. cookiesInfoVec.push_back(co);
  428. }
  429. std::string sendCookiesInfo = "";
  430. int cookiesCount = 0;
  431. for (auto& cookieInfo : cookiesInfoVec)
  432. {
  433. if (_url.find(cookieInfo.domain) != std::string::npos)
  434. {
  435. std::string keyValue = cookieInfo.key;
  436. keyValue.append("=");
  437. keyValue.append(cookieInfo.value);
  438. if (cookiesCount != 0)
  439. sendCookiesInfo.append(";");
  440. sendCookiesInfo.append(keyValue);
  441. }
  442. cookiesCount++;
  443. }
  444. //set Cookie
  445. addRequestHeader("Cookie",sendCookiesInfo.c_str());
  446. }
  447. void setReadAndConnectTimeout(int readMiliseconds, int connectMiliseconds)
  448. {
  449. JniMethodInfo methodInfo;
  450. if (JniHelper::getStaticMethodInfo(methodInfo,
  451. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  452. "setReadAndConnectTimeout",
  453. "(Ljava/net/HttpURLConnection;II)V"))
  454. {
  455. methodInfo.env->CallStaticVoidMethod(
  456. methodInfo.classID, methodInfo.methodID, _httpURLConnection, readMiliseconds, connectMiliseconds);
  457. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  458. }
  459. }
  460. void setVerifySSL()
  461. {
  462. if(_client->getSSLVerification().empty())
  463. return;
  464. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(_client->getSSLVerification());
  465. JniMethodInfo methodInfo;
  466. if (JniHelper::getStaticMethodInfo(methodInfo,
  467. "org/cocos2dx/lib/Cocos2dxHttpURLConnection",
  468. "setVerifySSL",
  469. "(Ljava/net/HttpURLConnection;Ljava/lang/String;)V"))
  470. {
  471. jstring jstrfullpath = methodInfo.env->NewStringUTF(fullpath.c_str());
  472. methodInfo.env->CallStaticVoidMethod(
  473. methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrfullpath);
  474. methodInfo.env->DeleteLocalRef(jstrfullpath);
  475. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  476. }
  477. }
  478. bool configure()
  479. {
  480. if(nullptr == _httpURLConnection)
  481. {
  482. return false;
  483. }
  484. if(nullptr == _client)
  485. {
  486. return false;
  487. }
  488. setReadAndConnectTimeout(_client->getTimeoutForRead() * 1000, _client->getTimeoutForConnect() * 1000);
  489. setVerifySSL();
  490. return true;
  491. }
  492. char* getBufferFromJString(jstring jstr, JNIEnv* env)
  493. {
  494. if (nullptr == jstr)
  495. {
  496. return nullptr;
  497. }
  498. std::string strValue = cocos2d::StringUtils::getStringUTFCharsJNI(env, jstr);
  499. return strdup(strValue.c_str());
  500. }
  501. int getCStrFromJByteArray(jbyteArray jba, JNIEnv* env, char** ppData)
  502. {
  503. if (nullptr == jba)
  504. {
  505. *ppData = nullptr;
  506. return 0;
  507. }
  508. int len = env->GetArrayLength(jba);
  509. char* str = (char*)malloc(sizeof(char)*len);
  510. env->GetByteArrayRegion(jba, 0, len, (jbyte*)str);
  511. *ppData = str;
  512. return len;
  513. }
  514. const std::string& getCookieString() const
  515. {
  516. return _responseCookies;
  517. }
  518. private:
  519. HttpClient* _client;
  520. jobject _httpURLConnection;
  521. std::string _requestmethod;
  522. std::string _responseCookies;
  523. std::string _cookieFileName;
  524. std::string _url;
  525. int _contentLength;
  526. };
  527. // Process Response
  528. void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
  529. {
  530. auto request = response->getHttpRequest();
  531. HttpRequest::Type requestType = request->getRequestType();
  532. if (HttpRequest::Type::GET != requestType &&
  533. HttpRequest::Type::POST != requestType &&
  534. HttpRequest::Type::PUT != requestType &&
  535. HttpRequest::Type::DELETE != requestType)
  536. {
  537. CCASSERT(true, "CCHttpClient: unknown request type, only GET、POST、PUT、DELETE are supported");
  538. return;
  539. }
  540. long responseCode = -1;
  541. int retValue = 0;
  542. HttpURLConnection urlConnection(this);
  543. if(!urlConnection.init(request))
  544. {
  545. response->setSucceed(false);
  546. response->setErrorBuffer("HttpURLConnetcion init failed");
  547. return;
  548. }
  549. switch (requestType)
  550. {
  551. case HttpRequest::Type::GET:
  552. urlConnection.setRequestMethod("GET");
  553. break;
  554. case HttpRequest::Type::POST:
  555. urlConnection.setRequestMethod("POST");
  556. break;
  557. case HttpRequest::Type::PUT:
  558. urlConnection.setRequestMethod("PUT");
  559. break;
  560. case HttpRequest::Type::DELETE:
  561. urlConnection.setRequestMethod("DELETE");
  562. break;
  563. default:
  564. break;
  565. }
  566. int suc = urlConnection.connect();
  567. if (0 != suc)
  568. {
  569. response->setSucceed(false);
  570. response->setErrorBuffer("connect failed");
  571. response->setResponseCode(responseCode);
  572. return;
  573. }
  574. if (HttpRequest::Type::POST == requestType ||
  575. HttpRequest::Type::PUT == requestType)
  576. {
  577. urlConnection.sendRequest(request);
  578. }
  579. responseCode = urlConnection.getResponseCode();
  580. if (0 == responseCode)
  581. {
  582. response->setSucceed(false);
  583. response->setErrorBuffer("connect failed");
  584. response->setResponseCode(-1);
  585. return;
  586. }
  587. char* headers = urlConnection.getResponseHeaders();
  588. if (nullptr != headers)
  589. {
  590. writeHeaderData(headers, strlen(headers), response);
  591. }
  592. free(headers);
  593. //get and save cookies
  594. char* cookiesInfo = urlConnection.getResponseHeaderByKey("set-cookie");
  595. if (nullptr != cookiesInfo)
  596. {
  597. urlConnection.saveResponseCookies(cookiesInfo, strlen(cookiesInfo));
  598. }
  599. free(cookiesInfo);
  600. //content len
  601. int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length");
  602. char* contentInfo = urlConnection.getResponseContent(response);
  603. if (nullptr != contentInfo)
  604. {
  605. std::vector<char> * recvBuffer = (std::vector<char>*)response->getResponseData();
  606. recvBuffer->clear();
  607. recvBuffer->insert(recvBuffer->begin(), (char*)contentInfo, ((char*)contentInfo) + urlConnection.getContentLength());
  608. }
  609. free(contentInfo);
  610. char *messageInfo = urlConnection.getResponseMessage();
  611. if (messageInfo)
  612. {
  613. strncpy(responseMessage, messageInfo, RESPONSE_BUFFER_SIZE-1);
  614. free(messageInfo);
  615. }
  616. urlConnection.disconnect();
  617. // write data to HttpResponse
  618. response->setResponseCode(responseCode);
  619. if (responseCode == -1)
  620. {
  621. response->setSucceed(false);
  622. response->setErrorBuffer(responseMessage);
  623. }
  624. else
  625. {
  626. response->setSucceed(true);
  627. }
  628. }
  629. // Worker thread
  630. void HttpClient::networkThread()
  631. {
  632. increaseThreadCount();
  633. while (true)
  634. {
  635. HttpRequest *request;
  636. // step 1: send http request if the requestQueue isn't empty
  637. {
  638. std::lock_guard<std::mutex> lock(_requestQueueMutex);
  639. while (_requestQueue.empty()) {
  640. _sleepCondition.wait(_requestQueueMutex);
  641. }
  642. request = _requestQueue.at(0);
  643. _requestQueue.erase(0);
  644. }
  645. if (request == _requestSentinel) {
  646. break;
  647. }
  648. // Create a HttpResponse object, the default setting is http access failed
  649. HttpResponse *response = new (std::nothrow) HttpResponse(request);
  650. processResponse(response, _responseMessage);
  651. // add response packet into queue
  652. _responseQueueMutex.lock();
  653. _responseQueue.pushBack(response);
  654. _responseQueueMutex.unlock();
  655. _schedulerMutex.lock();
  656. if (nullptr != _scheduler)
  657. {
  658. _scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
  659. }
  660. _schedulerMutex.unlock();
  661. }
  662. // cleanup: if worker thread received quit signal, clean up un-completed request queue
  663. _requestQueueMutex.lock();
  664. _requestQueue.clear();
  665. _requestQueueMutex.unlock();
  666. _responseQueueMutex.lock();
  667. _responseQueue.clear();
  668. _responseQueueMutex.unlock();
  669. decreaseThreadCountAndMayDeleteThis();
  670. }
  671. // Worker thread
  672. void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response)
  673. {
  674. increaseThreadCount();
  675. char responseMessage[RESPONSE_BUFFER_SIZE] = { 0 };
  676. processResponse(response, responseMessage);
  677. _schedulerMutex.lock();
  678. if (_scheduler != nullptr)
  679. {
  680. _scheduler->performFunctionInCocosThread([this, response, request]{
  681. const ccHttpRequestCallback& callback = request->getCallback();
  682. Ref* pTarget = request->getTarget();
  683. SEL_HttpResponse pSelector = request->getSelector();
  684. if (callback != nullptr)
  685. {
  686. callback(this, response);
  687. }
  688. else if (pTarget && pSelector)
  689. {
  690. (pTarget->*pSelector)(this, response);
  691. }
  692. response->release();
  693. // do not release in other thread
  694. request->release();
  695. });
  696. }
  697. _schedulerMutex.unlock();
  698. decreaseThreadCountAndMayDeleteThis();
  699. }
  700. // HttpClient implementation
  701. HttpClient* HttpClient::getInstance()
  702. {
  703. if (_httpClient == nullptr)
  704. {
  705. _httpClient = new (std::nothrow) HttpClient();
  706. }
  707. return _httpClient;
  708. }
  709. void HttpClient::destroyInstance()
  710. {
  711. if (_httpClient == nullptr)
  712. {
  713. CCLOG("HttpClient singleton is nullptr");
  714. return;
  715. }
  716. CCLOG("HttpClient::destroyInstance ...");
  717. auto thiz = _httpClient;
  718. _httpClient = nullptr;
  719. thiz->_scheduler->unscheduleAllForTarget(thiz);
  720. thiz->_schedulerMutex.lock();
  721. thiz->_scheduler = nullptr;
  722. thiz->_schedulerMutex.unlock();
  723. {
  724. std::lock_guard<std::mutex> lock(thiz->_requestQueueMutex);
  725. thiz->_requestQueue.pushBack(thiz->_requestSentinel);
  726. }
  727. thiz->_sleepCondition.notify_one();
  728. thiz->decreaseThreadCountAndMayDeleteThis();
  729. CCLOG("HttpClient::destroyInstance() finished!");
  730. }
  731. void HttpClient::enableCookies(const char* cookieFile)
  732. {
  733. std::lock_guard<std::mutex> lock(_cookieFileMutex);
  734. if (cookieFile)
  735. {
  736. _cookieFilename = std::string(cookieFile);
  737. }
  738. else
  739. {
  740. _cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
  741. }
  742. }
  743. void HttpClient::setSSLVerification(const std::string& caFile)
  744. {
  745. std::lock_guard<std::mutex> lock(_sslCaFileMutex);
  746. _sslCaFilename = caFile;
  747. }
  748. HttpClient::HttpClient()
  749. : _isInited(false)
  750. , _timeoutForConnect(30)
  751. , _timeoutForRead(60)
  752. , _threadCount(0)
  753. , _cookie(nullptr)
  754. , _requestSentinel(new HttpRequest())
  755. {
  756. CCLOG("In the constructor of HttpClient!");
  757. increaseThreadCount();
  758. _scheduler = Director::getInstance()->getScheduler();
  759. }
  760. HttpClient::~HttpClient()
  761. {
  762. CCLOG("In the destructor of HttpClient!");
  763. CC_SAFE_RELEASE(_requestSentinel);
  764. }
  765. //Lazy create semaphore & mutex & thread
  766. bool HttpClient::lazyInitThreadSemaphore()
  767. {
  768. if (_isInited)
  769. {
  770. return true;
  771. }
  772. else
  773. {
  774. auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this));
  775. t.detach();
  776. _isInited = true;
  777. }
  778. return true;
  779. }
  780. //Add a get task to queue
  781. void HttpClient::send(HttpRequest* request)
  782. {
  783. if (!lazyInitThreadSemaphore())
  784. {
  785. return;
  786. }
  787. if (nullptr == request)
  788. {
  789. return;
  790. }
  791. request->retain();
  792. _requestQueueMutex.lock();
  793. _requestQueue.pushBack(request);
  794. _requestQueueMutex.unlock();
  795. // Notify thread start to work
  796. _sleepCondition.notify_one();
  797. }
  798. void HttpClient::sendImmediate(HttpRequest* request)
  799. {
  800. if(nullptr == request)
  801. {
  802. return;
  803. }
  804. request->retain();
  805. // Create a HttpResponse object, the default setting is http access failed
  806. HttpResponse *response = new (std::nothrow) HttpResponse(request);
  807. auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response);
  808. t.detach();
  809. }
  810. // Poll and notify main thread if responses exists in queue
  811. void HttpClient::dispatchResponseCallbacks()
  812. {
  813. // log("CCHttpClient::dispatchResponseCallbacks is running");
  814. //occurs when cocos thread fires but the network thread has already quited
  815. HttpResponse* response = nullptr;
  816. _responseQueueMutex.lock();
  817. if (!_responseQueue.empty())
  818. {
  819. response = _responseQueue.at(0);
  820. _responseQueue.erase(0);
  821. }
  822. _responseQueueMutex.unlock();
  823. if (response)
  824. {
  825. HttpRequest *request = response->getHttpRequest();
  826. const ccHttpRequestCallback& callback = request->getCallback();
  827. Ref* pTarget = request->getTarget();
  828. SEL_HttpResponse pSelector = request->getSelector();
  829. if (callback != nullptr)
  830. {
  831. callback(this, response);
  832. }
  833. else if (pTarget && pSelector)
  834. {
  835. (pTarget->*pSelector)(this, response);
  836. }
  837. response->release();
  838. // do not release in other thread
  839. request->release();
  840. }
  841. }
  842. void HttpClient::increaseThreadCount()
  843. {
  844. _threadCountMutex.lock();
  845. ++_threadCount;
  846. _threadCountMutex.unlock();
  847. }
  848. void HttpClient::decreaseThreadCountAndMayDeleteThis()
  849. {
  850. bool needDeleteThis = false;
  851. _threadCountMutex.lock();
  852. --_threadCount;
  853. if (0 == _threadCount)
  854. {
  855. needDeleteThis = true;
  856. }
  857. _threadCountMutex.unlock();
  858. if (needDeleteThis)
  859. {
  860. delete this;
  861. }
  862. }
  863. void HttpClient::setTimeoutForConnect(int value)
  864. {
  865. std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
  866. _timeoutForConnect = value;
  867. }
  868. int HttpClient::getTimeoutForConnect()
  869. {
  870. std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
  871. return _timeoutForConnect;
  872. }
  873. void HttpClient::setTimeoutForRead(int value)
  874. {
  875. std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
  876. _timeoutForRead = value;
  877. }
  878. int HttpClient::getTimeoutForRead()
  879. {
  880. std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
  881. return _timeoutForRead;
  882. }
  883. const std::string& HttpClient::getCookieFilename()
  884. {
  885. std::lock_guard<std::mutex> lock(_cookieFileMutex);
  886. return _cookieFilename;
  887. }
  888. const std::string& HttpClient::getSSLVerification()
  889. {
  890. std::lock_guard<std::mutex> lock(_sslCaFileMutex);
  891. return _sslCaFilename;
  892. }
  893. }
  894. NS_CC_END
  895. #endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)