HttpJs.hx 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  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
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package haxe.http;
  23. #if js
  24. import js.html.XMLHttpRequestResponseType;
  25. import js.html.Blob;
  26. import haxe.io.Bytes;
  27. class HttpJs extends haxe.http.HttpBase {
  28. public var async:Bool;
  29. public var withCredentials:Bool;
  30. public var responseHeaders:Map<String, String>;
  31. var req:js.html.XMLHttpRequest;
  32. public function new(url:String) {
  33. async = true;
  34. withCredentials = false;
  35. super(url);
  36. }
  37. /**
  38. Cancels `this` Http request if `request` has been called and a response
  39. has not yet been received.
  40. **/
  41. public function cancel() {
  42. if (req == null)
  43. return;
  44. req.abort();
  45. req = null;
  46. }
  47. public override function request(?post:Bool) {
  48. this.responseAsString = null;
  49. this.responseBytes = null;
  50. this.responseHeaders = null;
  51. var r = req = js.Browser.createXMLHttpRequest();
  52. var onreadystatechange = function(_) {
  53. if (r.readyState != 4)
  54. return;
  55. var s = try r.status catch (e:Dynamic) null;
  56. if (s == 0 && js.Browser.supported && js.Browser.location != null) {
  57. // If the request is local and we have data: assume a success (jQuery approach):
  58. var protocol = js.Browser.location.protocol.toLowerCase();
  59. var rlocalProtocol = ~/^(?:about|app|app-storage|.+-extension|file|res|widget):$/;
  60. var isLocal = rlocalProtocol.match(protocol);
  61. if (isLocal) {
  62. s = r.response != null ? 200 : 404;
  63. }
  64. }
  65. if (s == js.Lib.undefined)
  66. s = null;
  67. if (s != null)
  68. onStatus(s);
  69. if (s != null && s >= 200 && s < 400) {
  70. req = null;
  71. // split headers and remove the last \r\n\r\n
  72. var headers = r.getAllResponseHeaders().split('\r\n');
  73. headers = headers.filter(h -> h != '');
  74. // store response headers
  75. responseHeaders = new haxe.ds.StringMap();
  76. for (hline in headers) {
  77. var a = hline.split(": ");
  78. var hname = a.shift();
  79. var hval = if (a.length == 1) a[0] else a.join(": ");
  80. hval = StringTools.ltrim(StringTools.rtrim(hval));
  81. responseHeaders.set(hname, hval);
  82. }
  83. success(Bytes.ofData(r.response));
  84. } else if (s == null || (s == 0 && r.response == null)) {
  85. req = null;
  86. onError("Failed to connect or resolve host");
  87. } else
  88. switch (s) {
  89. case 12029:
  90. req = null;
  91. onError("Failed to connect to host");
  92. case 12007:
  93. req = null;
  94. onError("Unknown host");
  95. default:
  96. req = null;
  97. responseBytes = r.response != null ? Bytes.ofData(r.response) : null;
  98. onError("Http Error #" + r.status);
  99. }
  100. };
  101. if (async)
  102. r.onreadystatechange = onreadystatechange;
  103. var uri:Null<Any> = switch [postData, postBytes] {
  104. case [null, null]: null;
  105. case [str, null]: str;
  106. case [null, bytes]: new Blob([bytes.getData()]);
  107. case _: null;
  108. }
  109. if (uri != null)
  110. post = true;
  111. else
  112. for (p in params) {
  113. if (uri == null)
  114. uri = "";
  115. else
  116. uri = uri + "&";
  117. uri = uri + StringTools.urlEncode(p.name) + "=" + StringTools.urlEncode(p.value);
  118. }
  119. try {
  120. if (post)
  121. r.open("POST", url, async);
  122. else if (uri != null) {
  123. var question = url.split("?").length <= 1;
  124. r.open("GET", url + (if (question) "?" else "&") + uri, async);
  125. uri = null;
  126. } else
  127. r.open("GET", url, async);
  128. r.responseType = ARRAYBUFFER;
  129. } catch (e:Dynamic) {
  130. req = null;
  131. onError(e.toString());
  132. return;
  133. }
  134. r.withCredentials = withCredentials;
  135. if (!Lambda.exists(headers, function(h) return h.name == "Content-Type") && post && postData == null)
  136. r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  137. for (h in headers)
  138. r.setRequestHeader(h.name, h.value);
  139. r.send(uri);
  140. if (!async)
  141. onreadystatechange(null);
  142. }
  143. /**
  144. Makes a synchronous request to `url`.
  145. This creates a new Http instance and makes a GET request by calling its
  146. `request(false)` method.
  147. If `url` is null, the result is unspecified.
  148. **/
  149. public static function requestUrl(url:String):String {
  150. var h = new Http(url);
  151. h.async = false;
  152. var r = null;
  153. h.onData = function(d) {
  154. r = d;
  155. }
  156. h.onError = function(e) {
  157. throw e;
  158. }
  159. h.request(false);
  160. return r;
  161. }
  162. }
  163. #end