laya-code-GameHttp

  • GameHttp.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
export class HTTP 
{
private callback:any;
private caller:any;

private http:Laya.HttpRequest;

constructor()
{
this.http = new Laya.HttpRequest;
}

public get(url:string, caller:any, callback:any) : HTTP
{
this.caller = caller;
this.callback = callback;
//this.http.once(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);
this.http.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
this.http.once(Laya.Event.ERROR, this, this.onHttpRequestError);
this.http.send(url, null, 'get', 'text');
return this;
}

public post(url:string,data:any,contentType:string,caller:any,callback:any):HTTP
{
this.caller = caller;
this.callback = callback;
//this.http.once(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);
this.http.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
this.http.once(Laya.Event.ERROR, this, this.onHttpRequestError);

if(contentType==null){
this.http.send(url, data, 'post', 'text');
}else{
this.http.send(url, data, 'post', 'text',["content-type",contentType]);
}

return this;
}

private onHttpRequestError(e: any): void
{
if(this.callback){
this.callback.apply(this.caller,[{state:500,msg:e}]);
}
}

private onHttpRequestComplete(e: any): void
{
if(this.callback){
this.callback.apply(this.caller,[{state:200,data:this.http.data}]);
}
}
}

export class GameHttp
{
// 执行http的get请求
// @url:要请求的url
// @caller:回调所属的类
// @callback:回调函数
public static RequestGet(url:string, caller:any, callback:any)
{
let http = new HTTP();
http.get(url, caller, callback);
}

// 执行http的post请求
// @url:要请求的url
// @data:要发送给请求url的数据
// @contentType:post请求的上下文类型
// @caller:回调所属的类
// @callback:回调函数
public static RequestPost(url:string, data:any, contentType:string, caller:any, callback:any)
{
let http = new HTTP();
http.post(url, data, contentType, caller, callback);
}
}
  • 使用
1
2
GameHttp.RequestPost("http://localhost:6789/test", "helloworld", "application/json;charset=UTF-8", this, null)
GameHttp.RequestGet('http://localhost:6789/test?a=dddd', this, null);