直接上重点 发送请求 const data = {}; const id = 'lee-12345678'; var params = `data=${data}id=${id}`; var request = new egret.HttpRequest(); request.responseType = egret.HttpResponseType.TEXT; request.open("url", egret.HttpMethod.PO
直接上重点
发送请求
const data = {};const id = 'lee-12345678';
var params = `data=${data}&id=${id}`;
var request = new egret.HttpRequest();
request.responseType = egret.HttpResponseType.TEXT;
request.open("url", egret.HttpMethod.POST); //设置为 POST 请求
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(params);
request.addEventListener(egret.Event.COMPLETE, this.onPostComplete, this);
request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onPostIOError, this);
request.addEventListener(egret.ProgressEvent.PROGRESS, this.onPostProgress, this);
监听请求状态
/*** 请求成功
*/
private onPostComplete(event: egret.Event): void {
var request = <egret.HttpRequest>event.currentTarget;
console.log("post data: ", request.response);
}
/**
* 请求失败
*/
private onPostIOError(event: egret.IOErrorEvent): void {
const text = 'POST data:\nError';
console.log(text, "post error: ", event);
}
/**
* 请求进度
*/
private onPostProgress(event: egret.ProgressEvent): void {
const text = Math.floor(100 * event.bytesLoaded / event.bytesTotal) + "%";
console.log("post progress: ", text);
}
请求加载文本
const request: egret.HttpRequest = new egret.HttpRequest();request.open("resource/default.res.json", egret.HttpMethod.GET);
request.send();
request.once(egret.Event.COMPLETE, respHandler, null);
request.once(egret.IOErrorEvent.IO_ERROR, respHandler, null);
request.once(egret.ProgressEvent.PROGRESS, progressHandler, null);
function respHandler (evt: egret.Event): void {
switch (evt.type) {
case egret.Event.COMPLETE:
const request: egret.HttpRequest = evt.currentTarget;
console.log("respHandler:n", request.response);
break;
case egret.IOErrorEvent.IO_ERROR:
console.log("respHandler io error");
break;
}
};
function progressHandler (evt: egret.ProgressEvent): void {
console.log("progress:", evt.bytesLoaded, evt.bytesTotal);
};
请求加载二进制文件
const request: egret.HttpRequest = new egret.HttpRequest();request.responseType = egret.HttpResponseType.ARRAY_BUFFER;
request.open("resource/assets/egret_icon.png", egret.HttpMethod.GET);
request.send();
request.once(egret.Event.COMPLETE, respHandler, null);
request.once(egret.IOErrorEvent.IO_ERROR, respHandler, null);
function respHandler(evt: egret.Event): void {
switch (evt.type) {
case egret.Event.COMPLETE:
const request: egret.HttpRequest = evt.currentTarget;
const ab: ArrayBuffer = request.response;
console.log("respHandler:n", ab.byteLength); // respHandler:n 6777
break;
case egret.IOErrorEvent.IO_ERROR:
console.log("respHandler io error");
break;
}
};