Created
February 26, 2019 12:41
-
-
Save sunny352/078c69bf3a832062f4599a6f36a8eb62 to your computer and use it in GitHub Desktop.
Egret的http请求封装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Http { | |
public static Inst(): Http { | |
if (null == Http._inst) { | |
Http._inst = new Http(); | |
} | |
return Http._inst; | |
} | |
private static _inst: Http; | |
public constructor() { | |
} | |
private token: string; | |
public Get(url: string, params: any, listener: Function, thisObject: any): void { | |
this.req(egret.HttpMethod.GET, url, params, listener, thisObject); | |
} | |
public Post(url: string, params: any, listener: Function, thisObject: any): void { | |
this.req(egret.HttpMethod.POST, url, params, listener, thisObject); | |
} | |
private req(method: string, url: string, params: any, listener: Function, thisObject: any) { | |
var request = new egret.HttpRequest(); | |
request.responseType = egret.HttpResponseType.TEXT; | |
var finalUrl = url; | |
var query = "" | |
if (null != params) { | |
query += Object.keys(params) | |
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])) | |
.join('&') | |
} | |
if (undefined != this.token) { | |
if ("" == query) { | |
query = "token=" + this.token; | |
} else { | |
query += "&token=" + this.token; | |
} | |
} | |
if ("" == query) { | |
request.open(url, method); | |
} else { | |
request.open(url + "?" + query, method); | |
} | |
var httpObj = this; | |
request.addEventListener(egret.Event.COMPLETE, function (event: egret.Event): void { | |
var request = <egret.HttpRequest>event.currentTarget; | |
var obj = JSON.parse(request.response) | |
if (null == obj) { | |
listener.call(thisObject, -2, null, null) | |
} else { | |
console.log(obj); | |
if (undefined != obj.t) { | |
httpObj.token = obj.t; | |
} | |
listener.call(thisObject, obj.code, obj.data, obj.err) | |
} | |
}, null); | |
request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onGetIOError, this); | |
request.addEventListener(egret.ProgressEvent.PROGRESS, this.onGetProgress, this); | |
request.send(); | |
} | |
private onGetIOError(event: egret.IOErrorEvent): void { | |
console.log("get error : " + event); | |
} | |
private onGetProgress(event: egret.ProgressEvent): void { | |
// console.log("get progress : " + Math.floor(100 * event.bytesLoaded / event.bytesTotal) + "%"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment