PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/cocos2d/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java

https://gitlab.com/gasabr/flappy-test
Java | 403 lines | 320 code | 54 blank | 29 comment | 60 complexity | 0a83e21921af9eb126defccfca9c248e MD5 | raw file
  1. /****************************************************************************
  2. Copyright (c) 2010-2014 cocos2d-x.org
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. package org.cocos2dx.lib;
  21. import android.util.Log;
  22. import java.io.BufferedInputStream;
  23. import java.io.ByteArrayOutputStream;
  24. import java.io.FileInputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.net.HttpURLConnection;
  29. import java.net.ProtocolException;
  30. import java.net.URL;
  31. import java.security.KeyStore;
  32. import java.security.cert.Certificate;
  33. import java.security.cert.CertificateFactory;
  34. import java.security.cert.X509Certificate;
  35. import java.text.ParseException;
  36. import java.text.SimpleDateFormat;
  37. import java.util.Calendar;
  38. import java.util.List;
  39. import java.util.Locale;
  40. import java.util.Map;
  41. import java.util.Map.Entry;
  42. import java.util.zip.GZIPInputStream;
  43. import java.util.zip.InflaterInputStream;
  44. import javax.net.ssl.HttpsURLConnection;
  45. import javax.net.ssl.SSLContext;
  46. import javax.net.ssl.TrustManagerFactory;
  47. public class Cocos2dxHttpURLConnection
  48. {
  49. private static final String POST_METHOD = "POST" ;
  50. private static final String PUT_METHOD = "PUT" ;
  51. static HttpURLConnection createHttpURLConnection(String linkURL) {
  52. URL url;
  53. HttpURLConnection urlConnection;
  54. try {
  55. url = new URL(linkURL);
  56. urlConnection = (HttpURLConnection) url.openConnection();
  57. //Accept-Encoding
  58. urlConnection.setRequestProperty("Accept-Encoding", "identity");
  59. urlConnection.setDoInput(true);
  60. } catch (Exception e) {
  61. Log.e("URLConnection exception", e.toString());
  62. return null;
  63. }
  64. return urlConnection;
  65. }
  66. static void setReadAndConnectTimeout(HttpURLConnection urlConnection, int readMiliseconds, int connectMiliseconds) {
  67. urlConnection.setReadTimeout(readMiliseconds);
  68. urlConnection.setConnectTimeout(connectMiliseconds);
  69. }
  70. static void setRequestMethod(HttpURLConnection urlConnection, String method){
  71. try {
  72. urlConnection.setRequestMethod(method);
  73. if(method.equalsIgnoreCase(POST_METHOD) || method.equalsIgnoreCase(PUT_METHOD)) {
  74. urlConnection.setDoOutput(true);
  75. }
  76. } catch (ProtocolException e) {
  77. Log.e("URLConnection exception", e.toString());
  78. }
  79. }
  80. static void setVerifySSL(HttpURLConnection urlConnection, String sslFilename) {
  81. if(!(urlConnection instanceof HttpsURLConnection))
  82. return;
  83. HttpsURLConnection httpsURLConnection = (HttpsURLConnection)urlConnection;
  84. try {
  85. InputStream caInput = null;
  86. if (sslFilename.startsWith("/")) {
  87. caInput = new BufferedInputStream(new FileInputStream(sslFilename));
  88. }else {
  89. String assetString = "assets/";
  90. String assetsfilenameString = sslFilename.substring(assetString.length());
  91. caInput = new BufferedInputStream(Cocos2dxHelper.getActivity().getAssets().open(assetsfilenameString));
  92. }
  93. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  94. Certificate ca;
  95. ca = cf.generateCertificate(caInput);
  96. System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
  97. caInput.close();
  98. // Create a KeyStore containing our trusted CAs
  99. String keyStoreType = KeyStore.getDefaultType();
  100. KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  101. keyStore.load(null, null);
  102. keyStore.setCertificateEntry("ca", ca);
  103. // Create a TrustManager that trusts the CAs in our KeyStore
  104. String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  105. TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  106. tmf.init(keyStore);
  107. // Create an SSLContext that uses our TrustManager
  108. SSLContext context = SSLContext.getInstance("TLS");
  109. context.init(null, tmf.getTrustManagers(), null);
  110. httpsURLConnection.setSSLSocketFactory(context.getSocketFactory());
  111. } catch (Exception e) {
  112. Log.e("URLConnection exception", e.toString());
  113. }
  114. }
  115. //Add header
  116. static void addRequestHeader(HttpURLConnection urlConnection, String key, String value) {
  117. urlConnection.setRequestProperty(key, value);
  118. }
  119. static int connect(HttpURLConnection http) {
  120. int suc = 0;
  121. try {
  122. http.connect();
  123. } catch (IOException e) {
  124. Log.e("cocos2d-x debug info", "come in connect");
  125. Log.e("cocos2d-x debug info", e.toString());
  126. suc = 1;
  127. }
  128. return suc;
  129. }
  130. static void disconnect(HttpURLConnection http) {
  131. http.disconnect();
  132. }
  133. static void sendRequest(HttpURLConnection http, byte[] byteArray) {
  134. try {
  135. OutputStream out = http.getOutputStream();
  136. if(null != byteArray) {
  137. out.write(byteArray);
  138. out.flush();
  139. }
  140. out.close();
  141. } catch (IOException e) {
  142. Log.e("URLConnection exception", e.toString());
  143. }
  144. }
  145. static String getResponseHeaders(HttpURLConnection http) {
  146. Map<String, List<String>> headers = http.getHeaderFields();
  147. if (null == headers) {
  148. return null;
  149. }
  150. String header = "";
  151. for (Entry<String, List<String>> entry: headers.entrySet()) {
  152. String key = entry.getKey();
  153. if (null == key) {
  154. header += listToString(entry.getValue(), ",") + "\n";
  155. } else {
  156. header += key + ":" + listToString(entry.getValue(), ",") + "\n";
  157. }
  158. }
  159. return header;
  160. }
  161. static String getResponseHeaderByIdx(HttpURLConnection http, int idx) {
  162. Map<String, List<String>> headers = http.getHeaderFields();
  163. if (null == headers) {
  164. return null;
  165. }
  166. String header = null;
  167. int counter = 0;
  168. for (Entry<String, List<String>> entry: headers.entrySet()) {
  169. if (counter == idx) {
  170. String key = entry.getKey();
  171. if (null == key) {
  172. header = listToString(entry.getValue(), ",") + "\n";
  173. } else {
  174. header = key + ":" + listToString(entry.getValue(), ",") + "\n";
  175. }
  176. break;
  177. }
  178. counter++;
  179. }
  180. return header;
  181. }
  182. static String getResponseHeaderByKey(HttpURLConnection http, String key) {
  183. if (null == key) {
  184. return null;
  185. }
  186. Map<String, List<String>> headers = http.getHeaderFields();
  187. if (null == headers) {
  188. return null;
  189. }
  190. String header = null;
  191. for (Entry<String, List<String>> entry: headers.entrySet()) {
  192. if (key.equalsIgnoreCase(entry.getKey())) {
  193. if ("set-cookie".equalsIgnoreCase(key)) {
  194. header = combinCookies(entry.getValue(), http.getURL().getHost());
  195. } else {
  196. header = listToString(entry.getValue(), ",");
  197. }
  198. break;
  199. }
  200. }
  201. return header;
  202. }
  203. static int getResponseHeaderByKeyInt(HttpURLConnection http, String key) {
  204. String value = http.getHeaderField(key);
  205. if (null == value) {
  206. return 0;
  207. } else {
  208. return Integer.parseInt(value);
  209. }
  210. }
  211. static byte[] getResponseContent(HttpURLConnection http) {
  212. InputStream in;
  213. try {
  214. in = http.getInputStream();
  215. String contentEncoding = http.getContentEncoding();
  216. if (contentEncoding != null) {
  217. if(contentEncoding.equalsIgnoreCase("gzip")){
  218. in = new GZIPInputStream(http.getInputStream()); //reads 2 bytes to determine GZIP stream!
  219. }
  220. else if(contentEncoding.equalsIgnoreCase("deflate")){
  221. in = new InflaterInputStream(http.getInputStream());
  222. }
  223. }
  224. } catch (IOException e) {
  225. in = http.getErrorStream();
  226. } catch (Exception e) {
  227. Log.e("URLConnection exception", e.toString());
  228. return null;
  229. }
  230. try {
  231. byte[] buffer = new byte[1024];
  232. int size = 0;
  233. ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
  234. while((size = in.read(buffer, 0 , 1024)) != -1)
  235. {
  236. bytestream.write(buffer, 0, size);
  237. }
  238. byte retbuffer[] = bytestream.toByteArray();
  239. bytestream.close();
  240. return retbuffer;
  241. } catch (Exception e) {
  242. Log.e("URLConnection exception", e.toString());
  243. }
  244. return null;
  245. }
  246. static int getResponseCode(HttpURLConnection http) {
  247. int code = 0;
  248. try {
  249. code = http.getResponseCode();
  250. } catch (IOException e) {
  251. Log.e("URLConnection exception", e.toString());
  252. }
  253. return code;
  254. }
  255. static String getResponseMessage(HttpURLConnection http) {
  256. String msg;
  257. try {
  258. msg = http.getResponseMessage();
  259. } catch (IOException e) {
  260. msg = e.toString();
  261. Log.e("URLConnection exception", msg);
  262. }
  263. return msg;
  264. }
  265. public static String listToString(List<String> list, String strInterVal) {
  266. if (list == null) {
  267. return null;
  268. }
  269. StringBuilder result = new StringBuilder();
  270. boolean flag = false;
  271. for (String str : list) {
  272. if (flag) {
  273. result.append(strInterVal);
  274. }
  275. if (null == str) {
  276. str = "";
  277. }
  278. result.append(str);
  279. flag = true;
  280. }
  281. return result.toString();
  282. }
  283. public static String combinCookies(List<String> list, String hostDomain) {
  284. StringBuilder sbCookies = new StringBuilder();
  285. String domain = hostDomain;
  286. String tailmatch = "FALSE";
  287. String path = "/";
  288. String secure = "FALSE";
  289. String key = null;
  290. String value = null;
  291. String expires = null;
  292. for (String str : list) {
  293. String[] parts = str.split(";");
  294. for (String part : parts) {
  295. int firstIndex = part.indexOf("=");
  296. if (-1 == firstIndex)
  297. continue;
  298. String[] item = {part.substring(0, firstIndex), part.substring(firstIndex + 1)};
  299. if ("expires".equalsIgnoreCase(item[0].trim())) {
  300. expires = str2Seconds(item[1].trim());
  301. } else if("path".equalsIgnoreCase(item[0].trim())) {
  302. path = item[1];
  303. } else if("secure".equalsIgnoreCase(item[0].trim())) {
  304. secure = item[1];
  305. } else if("domain".equalsIgnoreCase(item[0].trim())) {
  306. domain = item[1];
  307. } else if("version".equalsIgnoreCase(item[0].trim()) || "max-age".equalsIgnoreCase(item[0].trim())) {
  308. //do nothing
  309. } else {
  310. key = item[0];
  311. value = item[1];
  312. }
  313. }
  314. if (null == domain) {
  315. domain = "none";
  316. }
  317. sbCookies.append(domain);
  318. sbCookies.append('\t');
  319. sbCookies.append(tailmatch); //access
  320. sbCookies.append('\t');
  321. sbCookies.append(path); //path
  322. sbCookies.append('\t');
  323. sbCookies.append(secure); //secure
  324. sbCookies.append('\t');
  325. sbCookies.append(expires); //expires
  326. sbCookies.append("\t");
  327. sbCookies.append(key); //key
  328. sbCookies.append("\t");
  329. sbCookies.append(value); //value
  330. sbCookies.append('\n');
  331. }
  332. return sbCookies.toString();
  333. }
  334. private static String str2Seconds(String strTime) {
  335. Calendar c = Calendar.getInstance();
  336. long millisSecond = 0;
  337. try {
  338. c.setTime(new SimpleDateFormat("EEE, dd-MMM-yy hh:mm:ss zzz", Locale.US).parse(strTime));
  339. millisSecond = c.getTimeInMillis()/1000;
  340. } catch (ParseException e) {
  341. Log.e("URLConnection exception", e.toString());
  342. }
  343. return Long.toString(millisSecond);
  344. }
  345. }