当前位置 : 主页 > 编程语言 > java >

Egret Engine(一):发送HTTP请求

来源:互联网 收集:自由互联 发布时间:2022-07-17
直接上重点 发送请求 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;
}
};


上一篇:CF817C.Really Big Numbers(二分 思维)
下一篇:没有了
网友评论