HttpClient-android.cpp 32 KB

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