mirror of
https://github.com/NativeScript/NativeScript.git
synced 2025-11-05 13:26:48 +08:00
definitions fixed
This commit is contained in:
@@ -1,89 +1,129 @@
|
||||
/**
|
||||
* Android specific http request implementation.
|
||||
*/
|
||||
import promises = require("promises");
|
||||
* Android specific http request implementation.
|
||||
*/
|
||||
|
||||
import imageSource = require("image-source");
|
||||
import types = require("utils/types");
|
||||
|
||||
// this is imported for definition purposes only
|
||||
import http = require("http");
|
||||
import platform = require("platform");
|
||||
|
||||
export function request(options: http.HttpRequestOptions): promises.Promise<http.HttpResponse> {
|
||||
var d = promises.defer<http.HttpResponse>();
|
||||
var requestIdCounter = 0;
|
||||
var pendingRequests = {};
|
||||
|
||||
try {
|
||||
var request = new com.koushikdutta.async.http.AsyncHttpRequest(java.net.URI.create(options.url), options.method);
|
||||
|
||||
if (options.headers) {
|
||||
for (var key in options.headers) {
|
||||
request.addHeader(key, options.headers[key])
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof options.timeout == "number") {
|
||||
request.setTimeout(options.timeout);
|
||||
}
|
||||
|
||||
if (typeof options.content == "string") {
|
||||
var stringBody = com.koushikdutta.async.http.body.StringBody.extends({
|
||||
getContentType: function () {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
request.setBody(new stringBody(options.content));
|
||||
}
|
||||
else if (typeof options.content !== "undefined") {
|
||||
request.setBody(new com.koushikdutta.async.http.body.StreamBody(new java.io.ByteArrayInputStream(options.content), options.content.length));
|
||||
}
|
||||
|
||||
var callback = new com.koushikdutta.async.http.callback.HttpConnectCallback({
|
||||
onConnectCompleted: function (error, response) {
|
||||
if (error) {
|
||||
d.reject(new Error(error.toString()));
|
||||
} else {
|
||||
var headers = {};
|
||||
var rawHeaders = response.getHeaders().headers;
|
||||
|
||||
for (var i = 0, l = rawHeaders.length(); i < l; i++) {
|
||||
var key = rawHeaders.getFieldName(i);
|
||||
headers[key] = rawHeaders.getValue(i);
|
||||
}
|
||||
|
||||
var outputStream = new java.io.ByteArrayOutputStream();
|
||||
|
||||
var dataCallback = new com.koushikdutta.async.callback.DataCallback({
|
||||
onDataAvailable: function (emitter, byteBufferList) {
|
||||
var bb = byteBufferList.getAll();
|
||||
outputStream.write(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining());
|
||||
}
|
||||
});
|
||||
|
||||
response.setDataCallback(dataCallback);
|
||||
|
||||
var endCallback = new com.koushikdutta.async.callback.CompletedCallback({
|
||||
onCompleted: function (error) {
|
||||
d.resolve({
|
||||
content: {
|
||||
raw: outputStream,
|
||||
toString: () => { return outputStream.toString(); },
|
||||
toJSON: () => { return JSON.parse(outputStream.toString()); },
|
||||
toImage: () => {
|
||||
return require("image-source").fromData(new java.io.ByteArrayInputStream(outputStream.toByteArray()));
|
||||
}
|
||||
},
|
||||
statusCode: rawHeaders.getResponseCode(),
|
||||
headers: headers
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
response.setEndCallback(endCallback);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
com.koushikdutta.async.http.AsyncHttpClient.getDefaultInstance().execute(request, callback);
|
||||
|
||||
} catch (ex) {
|
||||
d.reject(ex);
|
||||
var completeCallback = new com.tns.Async.CompleteCallback({
|
||||
onComplete: function (result: any, context: any) {
|
||||
// as a context we will receive the id of the request
|
||||
onRequestComplete(context, result);
|
||||
}
|
||||
return d.promise();
|
||||
}
|
||||
});
|
||||
|
||||
function onRequestComplete(requestId: number, result: com.tns.Async.Http.RequestResult) {
|
||||
var callbacks = pendingRequests[requestId];
|
||||
delete pendingRequests[requestId];
|
||||
|
||||
if (result.error) {
|
||||
callbacks.rejectCallback(new Error(result.error.toString()));
|
||||
return;
|
||||
}
|
||||
|
||||
// read the headers
|
||||
var headers = {};
|
||||
if (result.headers) {
|
||||
var jHeaders = result.headers;
|
||||
var length = jHeaders.size();
|
||||
var i;
|
||||
var pair: com.tns.Async.Http.KeyValuePair;
|
||||
for (i = 0; i < length; i++) {
|
||||
pair = jHeaders.get(i);
|
||||
headers[pair.key] = pair.value;
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.resolveCallback({
|
||||
content: {
|
||||
raw: result.raw,
|
||||
toString: () => { return result.responseAsString; },
|
||||
toJSON: () => { return JSON.parse(result.responseAsString); },
|
||||
toImage: () => {
|
||||
return new Promise<imageSource.ImageSource>((resolveImage, rejectImage) => {
|
||||
if (result.responseAsImage != null) {
|
||||
resolveImage(imageSource.fromNativeSource(result.responseAsImage));
|
||||
}
|
||||
else {
|
||||
rejectImage(new Error("Response content may not be converted to an Image"));
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
statusCode: result.statusCode,
|
||||
headers: headers
|
||||
});
|
||||
}
|
||||
|
||||
function buildJavaOptions(options: http.HttpRequestOptions) {
|
||||
if (!types.isString(options.url)) {
|
||||
throw new Error("Http request must provide a valid url.");
|
||||
}
|
||||
|
||||
var javaOptions = new com.tns.Async.Http.RequestOptions();
|
||||
|
||||
javaOptions.url = options.url;
|
||||
if (types.isString(options.method)) {
|
||||
javaOptions.method = options.method;
|
||||
}
|
||||
if (options.content) {
|
||||
javaOptions.content = options.content;
|
||||
}
|
||||
if (types.isNumber(options.timeout)) {
|
||||
javaOptions.timeout = options.timeout;
|
||||
}
|
||||
|
||||
if (options.headers) {
|
||||
var arrayList = new java.util.ArrayList<com.tns.Async.Http.KeyValuePair>();
|
||||
var pair = com.tns.Async.Http.KeyValuePair;
|
||||
|
||||
for (var key in options.headers) {
|
||||
arrayList.add(new pair(key, options.headers[key]));
|
||||
}
|
||||
|
||||
javaOptions.headers = arrayList;
|
||||
}
|
||||
|
||||
// pass the maximum available image size to the request options in case we need a bitmap conversion
|
||||
var screen = platform.screen.mainScreen;
|
||||
javaOptions.screenWidth = screen.widthPixels;
|
||||
javaOptions.screenHeight = screen.heightPixels;
|
||||
|
||||
return javaOptions;
|
||||
}
|
||||
|
||||
export function request(options: http.HttpRequestOptions): Promise<http.HttpResponse> {
|
||||
if (!types.isDefined(options)) {
|
||||
// TODO: Shouldn't we throw an error here - defensive programming
|
||||
return;
|
||||
}
|
||||
return new Promise<http.HttpResponse>((resolve, reject) => {
|
||||
|
||||
try {
|
||||
// initialize the options
|
||||
var javaOptions = buildJavaOptions(options);
|
||||
|
||||
// remember the callbacks so that we can use them when the CompleteCallback is called
|
||||
var callbacks = {
|
||||
resolveCallback: resolve,
|
||||
rejectCallback: reject
|
||||
};
|
||||
pendingRequests[requestIdCounter] = callbacks;
|
||||
|
||||
//make the actual async call
|
||||
com.tns.Async.Http.MakeRequest(javaOptions, completeCallback, new java.lang.Integer(requestIdCounter));
|
||||
|
||||
// increment the id counter
|
||||
requestIdCounter++;
|
||||
} catch (ex) {
|
||||
reject(ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
4
http/http-request.d.ts
vendored
4
http/http-request.d.ts
vendored
@@ -1,5 +1,5 @@
|
||||
//@private
|
||||
import promises = require("promises");
|
||||
|
||||
import http = require("http");
|
||||
|
||||
export declare var request: (options: http.HttpRequestOptions) => promises.Promise<http.HttpResponse>;
|
||||
export declare var request: (options: http.HttpRequestOptions) => Promise<http.HttpResponse>;
|
||||
@@ -1,74 +1,83 @@
|
||||
/**
|
||||
* iOS specific http request implementation.
|
||||
*/
|
||||
import promises = require("promises");
|
||||
* iOS specific http request implementation.
|
||||
*/
|
||||
|
||||
import http = require("http");
|
||||
import imageSource = require("image-source");
|
||||
import types = require("utils/types");
|
||||
|
||||
export function request(options: http.HttpRequestOptions): promises.Promise<http.HttpResponse> {
|
||||
var d = promises.defer<http.HttpResponse>();
|
||||
var GET = "GET";
|
||||
var USER_AGENT_HEADER = "User-Agent";
|
||||
var USER_AGENT = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25";
|
||||
|
||||
try {
|
||||
var sessionConfig = Foundation.NSURLSessionConfiguration.defaultSessionConfiguration();
|
||||
var queue = Foundation.NSOperationQueue.mainQueue();
|
||||
var session = Foundation.NSURLSession.sessionWithConfigurationDelegateDelegateQueue(
|
||||
sessionConfig, null, queue);
|
||||
export function request(options: http.HttpRequestOptions): Promise<http.HttpResponse> {
|
||||
return new Promise<http.HttpResponse>((resolve, reject) => {
|
||||
|
||||
var urlRequest = Foundation.NSMutableURLRequest.requestWithURL(
|
||||
Foundation.NSURL.URLWithString(options.url));
|
||||
try {
|
||||
var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration();
|
||||
var queue = NSOperationQueue.mainQueue();
|
||||
var session = NSURLSession.sessionWithConfigurationDelegateDelegateQueue(
|
||||
sessionConfig, null, queue);
|
||||
|
||||
urlRequest.setHTTPMethod(typeof options.method !== "undefined" ? options.method : "GET");
|
||||
var urlRequest = NSMutableURLRequest.requestWithURL(
|
||||
NSURL.URLWithString(options.url));
|
||||
|
||||
if (options.headers) {
|
||||
for (var header in options.headers) {
|
||||
urlRequest.setValueForHTTPHeaderField(options.headers[header], header);
|
||||
}
|
||||
}
|
||||
urlRequest.HTTPMethod = types.isDefined(options.method) ? options.method : GET;
|
||||
|
||||
if (typeof options.timeout == "number") {
|
||||
urlRequest.setTimeoutInterval(options.timeout * 1000);
|
||||
}
|
||||
urlRequest.setValueForHTTPHeaderField(USER_AGENT, USER_AGENT_HEADER);
|
||||
|
||||
if (typeof options.content == "string") {
|
||||
urlRequest.setHTTPBody(Foundation.NSString.initWithString(options.content).dataUsingEncoding(4));
|
||||
}
|
||||
else if (typeof options.content !== "undefined") {
|
||||
urlRequest.setHTTPBody(options.content);
|
||||
}
|
||||
|
||||
var dataTask = session.dataTaskWithRequestCompletionHandler(urlRequest,
|
||||
function (data, response, error) {
|
||||
if (error) {
|
||||
d.reject(new Error(error.localizedDescription()));
|
||||
} else {
|
||||
var headers = {};
|
||||
var headerFields = response.allHeaderFields();
|
||||
var keys = headerFields.allKeys();
|
||||
|
||||
for (var i = 0, l = keys.count(); i < l; i++) {
|
||||
var key = keys.objectAtIndex(i);
|
||||
headers[key] = headerFields.valueForKey(key);
|
||||
}
|
||||
|
||||
d.resolve({
|
||||
content: {
|
||||
raw: data,
|
||||
toString: () => { return NSDataToString(data); },
|
||||
toJSON: () => { return JSON.parse(NSDataToString(data)); },
|
||||
toImage: () => { return require("image-source").fromData(data); }
|
||||
},
|
||||
statusCode: response.statusCode(),
|
||||
headers: headers
|
||||
});
|
||||
if (options.headers) {
|
||||
for (var header in options.headers) {
|
||||
urlRequest.setValueForHTTPHeaderField(options.headers[header], header);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
dataTask.resume();
|
||||
} catch (ex) {
|
||||
d.reject(ex);
|
||||
}
|
||||
return d.promise();
|
||||
if (types.isNumber(options.timeout)) {
|
||||
urlRequest.timeoutInterval = options.timeout * 1000;
|
||||
}
|
||||
|
||||
if (types.isString(options.content)) {
|
||||
urlRequest.HTTPBody = NSString.alloc().initWithString(options.content).dataUsingEncoding(4);
|
||||
}
|
||||
|
||||
var dataTask = session.dataTaskWithRequestCompletionHandler(urlRequest,
|
||||
function (data: NSData, response: NSHTTPURLResponse, error: NSError) {
|
||||
if (error) {
|
||||
reject(new Error(error.localizedDescription));
|
||||
} else {
|
||||
var headers = {};
|
||||
var headerFields = response.allHeaderFields;
|
||||
var keys = headerFields.allKeys;
|
||||
|
||||
for (var i = 0, l = keys.count; i < l; i++) {
|
||||
var key = keys.objectAtIndex(i);
|
||||
headers[key] = headerFields.valueForKey(key);
|
||||
}
|
||||
|
||||
resolve({
|
||||
content: {
|
||||
raw: data,
|
||||
toString: () => { return NSDataToString(data); },
|
||||
toJSON: () => { return JSON.parse(NSDataToString(data)); },
|
||||
toImage: () => {
|
||||
return new Promise<imageSource.ImageSource>((resolveImage, reject) => {
|
||||
resolveImage(imageSource.fromData(data));
|
||||
});
|
||||
}
|
||||
},
|
||||
statusCode: response.statusCode,
|
||||
headers: headers
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
dataTask.resume();
|
||||
} catch (ex) {
|
||||
reject(ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function NSDataToString(data: any): string {
|
||||
return Foundation.NSString.initWithDataEncoding(data, 4).toString();
|
||||
return NSString.alloc().initWithDataEncoding(data, 4).toString();
|
||||
}
|
||||
|
||||
75
http/http.d.ts
vendored
75
http/http.d.ts
vendored
@@ -1,121 +1,124 @@
|
||||
declare module "http" {
|
||||
/**
|
||||
* Allows you to send web requests and receive the responses.
|
||||
*/
|
||||
declare module "http" {
|
||||
import image = require("image-source");
|
||||
import promises = require("promises");
|
||||
|
||||
|
||||
/**
|
||||
/**
|
||||
* Downloads the content from the specified URL as a string.
|
||||
* @param url The URL to request from.
|
||||
*/
|
||||
function getString(url: string): promises.Promise<string>
|
||||
export function getString(url: string): Promise<string>
|
||||
|
||||
/**
|
||||
/**
|
||||
* Downloads the content from the specified URL as a string.
|
||||
* @param options An object that specifies various request options.
|
||||
*/
|
||||
function getString(options: HttpRequestOptions): promises.Promise<string>
|
||||
export function getString(options: HttpRequestOptions): Promise<string>
|
||||
|
||||
/**
|
||||
/**
|
||||
* Downloads the content from the specified URL as a string and returns its JSON.parse representation.
|
||||
* @param url The URL to request from.
|
||||
*/
|
||||
function getJSON<T>(url: string): promises.Promise<T>
|
||||
export function getJSON<T>(url: string): Promise<T>
|
||||
|
||||
/**
|
||||
/**
|
||||
* Downloads the content from the specified URL as a string and returns its JSON.parse representation.
|
||||
* @param options An object that specifies various request options.
|
||||
*/
|
||||
function getJSON<T>(options: HttpRequestOptions): promises.Promise<T>
|
||||
export function getJSON<T>(options: HttpRequestOptions): Promise<T>
|
||||
|
||||
/**
|
||||
/**
|
||||
* Downloads the content from the specified URL and attempts to decode it as an image.
|
||||
* @param url The URL to request from.
|
||||
*/
|
||||
function getImage(url: string): promises.Promise<image.ImageSource>
|
||||
export function getImage(url: string): Promise<image.ImageSource>
|
||||
|
||||
/**
|
||||
/**
|
||||
* Downloads the content from the specified URL and attempts to decode it as an image.
|
||||
* @param options An object that specifies various request options.
|
||||
*/
|
||||
function getImage(options: HttpRequestOptions): promises.Promise<image.ImageSource>
|
||||
export function getImage(options: HttpRequestOptions): Promise<image.ImageSource>
|
||||
|
||||
/**
|
||||
/**
|
||||
* Makes a generic http request using the provided options and returns a HttpResponse Object.
|
||||
* @param options An object that specifies various request options.
|
||||
*/
|
||||
function request(options: HttpRequestOptions): promises.Promise<HttpResponse>;
|
||||
export function request(options: HttpRequestOptions): Promise<HttpResponse>;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Provides options for the http requests.
|
||||
*/
|
||||
interface HttpRequestOptions {
|
||||
/**
|
||||
export interface HttpRequestOptions {
|
||||
/**
|
||||
* Gets or sets the request url.
|
||||
*/
|
||||
url: string;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets or sets the request method.
|
||||
*/
|
||||
method: string;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets or sets the request headers in JSON format.
|
||||
*/
|
||||
headers?: any;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets or sets the request body.
|
||||
*/
|
||||
content?: any;
|
||||
content?: string;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets or sets the request timeout.
|
||||
*/
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Encapsulates HTTP-response information from an HTTP-request.
|
||||
*/
|
||||
interface HttpResponse {
|
||||
/**
|
||||
export interface HttpResponse {
|
||||
/**
|
||||
* Gets the response status code.
|
||||
*/
|
||||
statusCode: number;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the response headers.
|
||||
*/
|
||||
headers: any;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the response content.
|
||||
*/
|
||||
content?: HttpContent;
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Encapsulates the content of an HttpResponse.
|
||||
*/
|
||||
interface HttpContent {
|
||||
/**
|
||||
export interface HttpContent {
|
||||
/**
|
||||
* Gets the response body as raw data.
|
||||
*/
|
||||
raw: any;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the response body as string.
|
||||
*/
|
||||
toString: () => string;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the response body as JSON object.
|
||||
*/
|
||||
toJSON: () => any;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the response body as ImageSource.
|
||||
*/
|
||||
toImage: () => image.ImageSource;
|
||||
toImage: () => Promise<image.ImageSource>;
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import image = require("image-source");
|
||||
import promises = require("promises");
|
||||
import request = require("http/http-request");
|
||||
|
||||
// merge the exports of the request file with the exports of this file
|
||||
declare var exports;
|
||||
require("utils/module-merge").merge(request, exports);
|
||||
|
||||
export function getString(arg: any): promises.Promise<string> {
|
||||
var d = promises.defer<string>();
|
||||
|
||||
request.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg)
|
||||
.then(r => d.resolve(r.content.toString()))
|
||||
.fail(e => d.reject(e));
|
||||
|
||||
return d.promise();
|
||||
}
|
||||
|
||||
export function getJSON<T>(arg: any): promises.Promise<T> {
|
||||
var d = promises.defer<T>();
|
||||
|
||||
request.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg)
|
||||
.then(r => d.resolve(r.content.toJSON()))
|
||||
.fail(e => d.reject(e));
|
||||
|
||||
return d.promise();
|
||||
}
|
||||
|
||||
export function getImage(arg: any): promises.Promise<image.ImageSource> {
|
||||
var d = promises.defer<image.ImageSource>();
|
||||
|
||||
request.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg)
|
||||
.then(r => d.resolve(r.content.toImage()))
|
||||
.fail(e => d.reject(e));
|
||||
|
||||
return d.promise();
|
||||
}
|
||||
233
http/http.ts
Normal file
233
http/http.ts
Normal file
@@ -0,0 +1,233 @@
|
||||
import image = require("image-source");
|
||||
|
||||
import definition = require("http");
|
||||
import httpRequest = require("http/http-request");
|
||||
|
||||
import types = require("utils/types");
|
||||
|
||||
// merge the exports of the request file with the exports of this file
|
||||
declare var exports;
|
||||
require("utils/module-merge").merge(httpRequest, exports);
|
||||
|
||||
export function getString(arg: any): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
httpRequest.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg)
|
||||
.then(r => resolve(r.content.toString()), e => reject(e));
|
||||
});
|
||||
}
|
||||
|
||||
export function getJSON<T>(arg: any): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
httpRequest.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg)
|
||||
.then(r => resolve(r.content.toJSON()), e => reject(e));
|
||||
});
|
||||
}
|
||||
|
||||
export function getImage(arg: any): Promise<image.ImageSource> {
|
||||
return new Promise<image.ImageSource>((resolve, reject) => {
|
||||
httpRequest.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg)
|
||||
.then(r => {
|
||||
r.content.toImage().then(source => resolve(source));
|
||||
}, e => reject(e));
|
||||
});
|
||||
}
|
||||
|
||||
export class XMLHttpRequest {
|
||||
public UNSENT = 0;
|
||||
public OPENED = 1;
|
||||
public HEADERS_RECEIVED = 2;
|
||||
public LOADING = 3;
|
||||
public DONE = 4;
|
||||
|
||||
private _options: definition.HttpRequestOptions;
|
||||
private _readyState: number;
|
||||
private _status: number;
|
||||
private _response: any;
|
||||
private _responseText: string = "";
|
||||
private _headers: any;
|
||||
private _errorFlag: boolean;
|
||||
|
||||
public onreadystatechange: Function;
|
||||
|
||||
constructor() {
|
||||
this._readyState = this.UNSENT;
|
||||
}
|
||||
|
||||
public open(method: string, url: string, async?: boolean, user?: string, password?: string) {
|
||||
if (types.isString(method) && types.isString(url)) {
|
||||
this._options = { url: url, method: method };
|
||||
this._options.headers = {};
|
||||
|
||||
if (types.isString(user)) {
|
||||
this._options.headers["user"] = user;
|
||||
}
|
||||
|
||||
if (types.isString(password)) {
|
||||
this._options.headers["password"] = password;
|
||||
}
|
||||
|
||||
this._setReadyState(this.OPENED);
|
||||
}
|
||||
}
|
||||
|
||||
public abort() {
|
||||
this._errorFlag = true;
|
||||
|
||||
this._response = null;
|
||||
this._responseText = null;
|
||||
this._headers = null;
|
||||
this._status = null;
|
||||
|
||||
if (this._readyState === this.UNSENT || this._readyState === this.OPENED || this._readyState === this.DONE) {
|
||||
this._readyState = this.UNSENT;
|
||||
} else {
|
||||
this._setReadyState(this.DONE);
|
||||
}
|
||||
}
|
||||
|
||||
public send(data?: string) {
|
||||
this._errorFlag = false;
|
||||
this._response = null;
|
||||
this._responseText = null;
|
||||
this._headers = null;
|
||||
this._status = null;
|
||||
|
||||
if (types.isDefined(this._options)) {
|
||||
if (types.isString(data)) {
|
||||
this._options.content = data;
|
||||
}
|
||||
|
||||
httpRequest.request(this._options).then(r=> {
|
||||
if (!this._errorFlag) {
|
||||
this._status = r.statusCode;
|
||||
this._response = r.content.raw;
|
||||
|
||||
this._headers = r.headers;
|
||||
this._setReadyState(this.HEADERS_RECEIVED);
|
||||
|
||||
this._setReadyState(this.LOADING);
|
||||
|
||||
this._responseText = r.content.toString();
|
||||
this._setReadyState(this.DONE);
|
||||
}
|
||||
|
||||
}).catch(e => {
|
||||
this._errorFlag = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public setRequestHeader(header: string, value: string) {
|
||||
if (types.isDefined(this._options) && types.isString(header) && types.isString(value)) {
|
||||
this._options.headers[header] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public getAllResponseHeaders(): string {
|
||||
if (this._readyState < 2 || this._errorFlag) {
|
||||
return "";
|
||||
}
|
||||
|
||||
var result = "";
|
||||
|
||||
for (var i in this._headers) {
|
||||
// Cookie headers are excluded
|
||||
if (i !== "set-cookie" && i !== "set-cookie2") {
|
||||
result += i + ": " + this._headers[i] + "\r\n";
|
||||
}
|
||||
}
|
||||
return result.substr(0, result.length - 2);
|
||||
}
|
||||
|
||||
public getResponseHeader(header: string): string {
|
||||
if (types.isString(header) && this._readyState > 1
|
||||
&& this._headers
|
||||
&& this._headers[header]
|
||||
&& !this._errorFlag
|
||||
) {
|
||||
return this._headers[header];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public overrideMimeType(mime: string) {
|
||||
//
|
||||
}
|
||||
|
||||
get readyState(): number {
|
||||
return this._readyState;
|
||||
}
|
||||
|
||||
private _setReadyState(value: number) {
|
||||
if (this._readyState !== value) {
|
||||
this._readyState = value;
|
||||
|
||||
if (types.isFunction(this.onreadystatechange)) {
|
||||
this.onreadystatechange();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get responseText(): string {
|
||||
return this._responseText;
|
||||
}
|
||||
|
||||
get response(): any {
|
||||
return this._response;
|
||||
}
|
||||
|
||||
get status(): number {
|
||||
return this._status;
|
||||
}
|
||||
|
||||
get statusText(): string {
|
||||
if (this._readyState === this.UNSENT || this._readyState === this.OPENED || this._errorFlag) {
|
||||
return "";
|
||||
}
|
||||
return this._status + " " + statuses[this._status];
|
||||
}
|
||||
}
|
||||
|
||||
var statuses = {
|
||||
100: "Continue",
|
||||
101: "Switching Protocols",
|
||||
200: "OK",
|
||||
201: "Created",
|
||||
202: "Accepted",
|
||||
203: "Non - Authoritative Information",
|
||||
204: "No Content",
|
||||
205: "Reset Content",
|
||||
206: "Partial Content",
|
||||
300: "Multiple Choices",
|
||||
301: "Moved Permanently",
|
||||
302: "Found",
|
||||
303: "See Other",
|
||||
304: "Not Modified",
|
||||
305: "Use Proxy",
|
||||
307: "Temporary Redirect",
|
||||
400: "Bad Request",
|
||||
401: "Unauthorized",
|
||||
402: "Payment Required",
|
||||
403: "Forbidden",
|
||||
404: "Not Found",
|
||||
405: "Method Not Allowed",
|
||||
406: "Not Acceptable",
|
||||
407: "Proxy Authentication Required",
|
||||
408: "Request Timeout",
|
||||
409: "Conflict",
|
||||
410: "Gone",
|
||||
411: "Length Required",
|
||||
412: "Precondition Failed",
|
||||
413: "Request Entity Too Large",
|
||||
414: "Request - URI Too Long",
|
||||
415: "Unsupported Media Type",
|
||||
416: "Requested Range Not Satisfiable",
|
||||
417: "Expectation Failed",
|
||||
500: "Internal Server Error",
|
||||
501: "Not Implemented",
|
||||
502: "Bad Gateway",
|
||||
503: "Service Unavailable",
|
||||
504: "Gateway Timeout",
|
||||
505: "HTTP Version Not Supported"
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
declare var module, require;
|
||||
module.exports = require("http/http");
|
||||
2
http/package.json
Normal file
2
http/package.json
Normal file
@@ -0,0 +1,2 @@
|
||||
{ "name" : "http",
|
||||
"main" : "http.js" }
|
||||
Reference in New Issue
Block a user