Egret HTTP简单请求

在游戏使用的网络请求,http协议,常用的get、post方法实例

参考官方文档

GET方法

新建请求对象,设置参数,请求方法,注册监听事件

1
2
3
4
5
6
7
8
9
10
11
let params = `?gameId=${userAccountInfo.gameId}&accesstoken=${userAccountInfo.token}&userId=${userAccountInfo.userId}`
let request = new egret.HttpRequest()

let url = `${SoloGame.baseURL}gameRanking.do${params}`

request.open(`http://${SoloGame.baseURL}userCenter.do${params}`, egret.HttpMethod.GET)

request.send()
request.addEventListener(egret.Event.COMPLETE, this.onGetUserInfoComplete, this)
request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onGetUserInfoError, this)
request.addEventListener(egret.ProgressEvent.PROGRESS, this.onGetUserInfoProgress, this)

监听请求状态,成功、失败、进度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private onGetUserInfoComplete(event: egret.Event): void {
var request = <egret.HttpRequest>event.currentTarget
let result = JSON.parse(request.response)
if (result.status == 200) {
//TODO
}
}

private onGetUserInfoError(event: egret.IOErrorEvent): void {
console.log("get error : " + event);
}

private onGetUserInfoProgress(event: egret.ProgressEvent): void {
console.log("get progress : " + Math.floor(100 * event.bytesLoaded / event.bytesTotal) + "%");
}

POST方法

1
2
3
4
5
6
7
8
9
10
11
12
13
let params = `gameId=${userAccountInfo.gameId}&accesstoken=${userAccountInfo.token}&userId=${userAccountInfo.userId}&isSlot=1&wealth=${spinCoins}`
let request = new egret.HttpRequest()

let url = SoloGame.SPINREQUEST

request.open(`http://${url}`, egret.HttpMethod.POST)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

request.send(params)

request.addEventListener(egret.Event.COMPLETE, this.onSpinGetComplete, this)
request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onSpinGetIOError, this)
request.addEventListener(egret.ProgressEvent.PROGRESS, this.onSpinGetProgress, this)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private onSpinGetComplete(event: egret.Event): void {
var request = <egret.HttpRequest>event.currentTarget
let result = JSON.parse(request.response)

if (result.status == 200) {
//TODO
} else {
SoloGame.SPINRESULT = ''
}
}

private onSpinGetIOError(event: egret.IOErrorEvent): void {
console.log("get error : " + event);
}
private onSpinGetProgress(event: egret.ProgressEvent): void {
console.log("get progress : " + Math.floor(100 * event.bytesLoaded / event.bytesTotal) + "%");
}