Egret 2D(8) Network

Egret encapsulates XMLHttpRequest for asynchronous data exchange.

basic process

The HTTP communication mechanism has to go through the following steps:

A TCP connection is established.
The web browser sends a request command to the web server.
The web browser sends the request header information . The
web server responds .
The web server sends the response header information. The
web server sends data to the browser. The
web server closes the TCP connection (if the request header is set to Connection :keep-alive will keep the connection still open).

send request

There are GET and POST methods for sending requests :

egret.HttpMethod.GET

egret.HttpMethod.POST

Egret uses the HttpRequest class to send HTTP requests. The request method can be specified as GET or POST. Server-side responses can be detected by listening for load events. The process of using HttpRequest to send a request is as follows:

  • Instantiate an HttpRequest object.
  • Set its response type responseType.
  • Initially request an object through the open method, initialize the request address and request type.
  • Set the request header information through setRequestHeader. If it is a POST request with parameters, this step is very important, you need to tell the server the parameter format of the request, and this step needs to be executed after open.
  • Send the request through the send method, and if it is the post method, you can pass in parameters.
  • Add a listener to listen for server-side responses, including progress events and request success and failure events.
private createGameScene() {
           //实例化一个HttpRequest对象
           var request = new egret.HttpRequest();
           //设置响应类型responseType
           request.responseType = egret.HttpResponseType.TEXT;
           //open方法初始化一个请求对象,参数为请求为请求地址和请求类型
           request.open("http://httpbin.org/get",egret.HttpMethod.GET);
           //设置请求头信息。如果是POST带参数的请求这一步很重要,需要告诉服务端请求的参数格式,而且这一步需要在 open 之后执行
           request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
           //send发送请求,如果是 post 方法可以传入参数。
           request.send();
           //监听请求事件
           //监听请求成功
           request.addEventListener(egret.Event.COMPLETE,this.onGetComplete,this);
           //监听请求失败
           request.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onGetIOError,this); 
           //监听请求进度
           request.addEventListener(egret.ProgressEvent.PROGRESS,this.onGetProgress,this);

   }
   //请求成功
   private onGetComplete(event:egret.Event):void{
      //获取请求对象 
      var request = <egret.HttpRequest>event.currentTarget;
      //获取返回的信息
      var data=request.response;
      console.log(data)

   }
   //请求失败
   private onGetIOError(event:egret.Event):void{
         console.log("error :" + event);
   }
    //请求进度
    private onGetProgress(event:egret.Event):void{
      console.log("progress : " + Math.floor(100*(event as any).bytesLoaded/(<any>event).bytesTotal) + "%");
   }

send request with parameters

Format of sending data: The data sent by the HTTP client is generally composed of key and value, and multiple data are connected with &. After splicing, the following form is formed

key1=value1&key2=valueP2

The parameters sent by the GET method will be added to the back of the URL and spliced ​​together, and separated by ?. The parameters sent by the POST method need to first set the header information of the HTTP request to tell the server in what form the data is sent. The most common one we use is application/x-www-form-urlencoded, which means that we format parameters by key and value. The server can also use the same method to get parameters.

The first is the GET request. The GET request needs to be implemented by splicing the parameters behind the URL. The ? link is required between the URL and the parameter

GET method:

//拼接参数 
var params = "?p1=getP1&p2=getP2";
var request = new egret.HttpRequest();
request.responseType = egret.HttpResponseType.TEXT;
//将参数拼接到url
request.open("php/get_test.php"+params,egret.HttpMethod.GET);
request.send();

POST method:

Send a POST request. It should be noted that sending a POST request requires the parameters to be sent in the parameters of the send method. And to set its response header, in our example, use the key value method to format the parameters, here we need to set the response header Content-Type to application/x-www-form-urlencoded

//拼接参数
var params = "p1=postP1&p2=postP2";
var request = new egret.HttpRequest();
request.responseType = egret.HttpResponseType.TEXT;
request.open("php/post_test.php",egret.HttpMethod.POST);
//设置响应头
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//发送参数
request.send(params);

Load bitmap file

Egret provides the ImageLoader class for loading bitmap files.

For example, the ImageLoader class loads the image at 'resource/egret.png' with the following code:

var imgLoader:egret.ImageLoader = new egret.ImageLoader;
imgLoader.once( egret.Event.COMPLETE, this.imgLoadHandler, this ); 
imgLoader.load( "resource/egret.png" );



//在所定义的回调事件中,可以用下面的方式获取该图片对应的 BitmapData,并以此来创建位图:

public imgLoadHandler( evt:egret.Event ):void{
    var loader:egret.ImageLoader = evt.currentTarget;
    var bmd:egret.BitmapData = loader.data;
    var bmp:egret.Bitmap = new egret.Bitmap( bmd );
    this.addChild(bmp);
}

Cross-domain processing:

1.服务器设置访问权限
2.可以通过尝试修改 imgLoader.crossOrigin = 'anonymous' 来以匿名的方式访问。不过在使用 texture.toDataURL 时会报跨域问题。
3.Webgl 渲染下,暂不支持跨域图片处理。

load text 

The core methods of the HttpRequest object are open() and send(). The open() method receives the URL to be accessed by the request. As an option, you can also pass in the loading method. This parameter is usually taken as a constant with HttpMethod, and the default is the most commonly used GET method.
When the loading is complete, the returned data is obtained through the response property of the HttpRequest object.

var url = "resource/config/description.json";
var  request:egret.HttpRequest = new egret.HttpRequest();
var respHandler = function( evt:egret.Event ):void{
   switch ( evt.type ){
       case egret.Event.COMPLETE:
           var request:egret.HttpRequest = evt.currentTarget;
           console.log( "respHandler:n", request.response );
           break;
       case egret.IOErrorEvent.IO_ERROR:
           console.log( "respHandler io error" );
           break;
   }
}
var progressHandler = function( evt:egret.ProgressEvent ):void{
   console.log( "progress:", evt.bytesLoaded, evt.bytesTotal );
}
request.once( egret.Event.COMPLETE, respHandler, null);
request.once( egret.IOErrorEvent.IO_ERROR, respHandler, null);
request.once( egret.ProgressEvent.PROGRESS, progressHandler, null);
request.open( url, egret.HttpMethod.GET ); 
request.send( );

The default load type of HttpRequest is TEXT, so no special setting is required.
The main event that needs to be listened to is COMPLETE, from which the data is fetched.
To account for unexpected situations, do the handling of these situations in IO_ERROR.
The loading progress event is ProgressEvent.PROGRESS , which is useful when loading resources with large content.

load binary

var url = "resource/assets/egret_icon.png";
var  request:egret.HttpRequest = new egret.HttpRequest();
request.responseType = egret.HttpResponseType.ARRAY_BUFFER;
var respHandler = function( evt:egret.Event ):void {
   switch ( evt.type ){
       case egret.Event.COMPLETE:
           var request:egret.HttpRequest = evt.currentTarget;
           var ab:ArrayBuffer = request.response;
           console.log( "respHandler:n", ab.byteLength );
           break;
       case egret.IOErrorEvent.IO_ERROR:
           console.log( "respHandler io error" );
           break;
   }
}
request.once( egret.Event.COMPLETE, respHandler, null);
request.once( egret.IOErrorEvent.IO_ERROR, respHandler, null);
request.open( url, egret.HttpMethod.GET );
request.send( );

To load binary data, first set the load type of HttpRequest to ARRAY_BUFFER.
After the data is loaded, the ArrayBuffer object can be obtained from the response property, and further reading operations can be performed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324418447&siteId=291194637