[Reserved] UnityWebRequest initial use and common analytical method

Source: https://blog.csdn.net/qwe25878/article/details/85051911#_35

Today, to learn about a new network requests Unity UnityWebRequest way
or the old rules, look at the description.

 

description

UnityWebRequest object is used to communicate with the Web server.

UnityWebRequests processing an HTTP Web server traffic. Other objects - especially DownloadHandler and UploadHandler - managed separately download and upload data.

Note : Once UnityWebRequest start by calling the Send method of communicating with a remote server, most of the properties on UnityWebRequest object can not be changed. (Send out of date, an example of the method described herein below)

start using

By reading UnityWebRequest official API discovery, or with a lot of functions, we pick some common speak.

Construction method

public UnityWebRequest();
public UnityWebRequest(string url);
public UnityWebRequest(Uri uri);
public UnityWebRequest(string url, string method);
public UnityWebRequest(Uri uri, string method);
public UnityWebRequest(string url, string method, Networking.DownloadHandler downloadHandler, Networking.UploadHandler uploadHandler);
public UnityWebRequest(Uri uri, string method, Networking.DownloadHandler downloadHandler, Networking.UploadHandler uploadHandler);

These are very common construction method is common, there is not too much to say, in fact, if not special needs, I personally recommend using these very methods to construct UnityWebRequest object.

Other examples of methods

In fact UnityWebRequest us encapsulates some common public static method, we can to build a UnityWebRequest by these public static method.
Commonly used are:
the Delete
the Get
Head
Post
of Put
read the documentation can be found, these methods will return a package Networking.UnityWebRequest object.
In this way, we can construct our UnityWebRequest objects through these methods.

A simple example

I wrote a script that contains a simple get and post requests might be more intuitive.

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class Network : MonoBehaviour {

    void Start () 
    {
        StartCoroutine(Get());
       	StartCoroutine(Post());
    }

    IEnumerator Get()
    {
        UnityWebRequest webRequest = UnityWebRequest.Get("http://www.baidu.com");

        yield return webRequest.SendWebRequest();
        //异常处理,很多博文用了error!=null这是错误的,请看下文其他属性部分
       if (webRequest.isHttpError||webRequest.isNetworkError)
            Debug.Log(webRequest.error);
        else 
        {
            Debug.Log(webRequest.downloadHandler.text);
        }

    }

    IEnumerator Post()
    {
        WWWForm form = new WWWForm();
        //键值对
        form.AddField("key", "value");
        form.AddField("name","mafanwei");
        form.AddField("blog","qwe25878");

        UnityWebRequest webRequest = UnityWebRequest.Post("http://www.baidu.com",form);

        yield return webRequest.SendWebRequest();
        //异常处理,很多博文用了error!=null这是错误的,请看下文其他属性部分
        if (webRequest.isHttpError||webRequest.isNetworkError)
            Debug.Log(webRequest.error);
        else
        {
            Debug.Log(webRequest.downloadHandler.text);
        }
    }

}

Parsing script

In fact, the above simple script has met our needs in most cases, the following speaking about the script above principle.
As used herein, the Unity coroutine IEnumerator.
What coroutine that?
Coroutine is suspended can return immediately after the pause function until after the completion of the interrupt instruction to continue execution.
By yield return, we can make him pause here, and then had to return to continue until the following code.
webRequest.SendWebRequest () This method is to start communicating with a remote server. Calling this method is the
UnityWebRequest DNS resolution will be performed (if necessary), the HTTP request to the remote server and processing at the destination URL of the server response. WebRequestAsyncOperation it returns the object, it will lead to generation WebRequestAsyncOperation coroutine suspended within a coroutine, until it encounters a system error or completion UnityWebRequest communication.
Through this, we realize there are things running when UnityWebRequest after the completion of the following handling code.
Note :
1. After calling this method, we can not change the properties of any UnityWebRequest.
2. This method can only be called once on any given UnityWebRequest object.

Other common methods

public void Abort();

It will end as soon as possible the process of networking, this method can be called at any time. If UnityWebRequest has not been completed, UnityWebRequest will stop uploading or downloading data as soon as possible. The suspension is considered UnityWebRequests encountered a system error. isNetworkError or isHttpError property returns true, error property will be "User Aborted".

If you call this method before calling Send, then UnityWebRequest aborted immediately after the call Send.

After this UnityWebRequest encounter other errors or completed successfully communicate with a remote server, a call to this method is not valid.

public static string EscapeURL(string s);
public static string EscapeURL(string s, Encoding e);

Escape characters in the string to make sure they are friendly URL.

Some text characters have special meaning in the presence of the URL. If you need to include these characters in the URL parameter, you must use the escape sequences represent them. We recommend that you pass the URL parameter before any text provided by the user to use this function as text. This will ensure that malicious users can not manipulate the contents of the URL to attack the Web server. We can also use the URL translation UnityWebRequest.UnEscapeURL to come back.
:( http example in the ampersand character has a special meaning to link two variables)

using UnityEngine;
using UnityEngine.Networking;

public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        string escName = UnityWebRequest.EscapeURL("Fish & Chips");
    }
}
public void Dispose();

That is no longer using this UnityWebRequest, and should clean up any resources it is using.

Whether the request succeeded or failed, we must call Dispose after the completion of use UnityWebRequest object.

Note : But that does not mean we all need to call this method every time. Because Unity provides us disposeDownloadHandlerOnDispose and disposeUploadHandlerOnDispose two bool type attributes. Their default value is true, that is, we do not need to set up Unity will automatically call Dispose after the completion of () to release resources.

Other common attributes

public int timeout;

The UnityWebRequest set in the timeout in seconds after attempting to abort.

When a timeout occurs, an error is returned "Request timed out." When the timeout is set to 0, the timeout does not apply. This property defaults to 0.
Note : Set the timeout may apply to each URL redirects on Android, which may lead to longer response.

isHttpError

Returns true after the response code indicating the receipt of this error UnityWebRequest HTTP. (Read Only)

If the response code is greater than or equal to 400, compared to True.

isNetworkError

Returns true after UnityWebRequest encountered a system error. (Read Only)

Examples include a system error can not be resolved DNS entry, socket errors or redirection limit exceeded. When this property returns true, error property contains a string describing the error-readable.

Note: the type of error codes returned by the server (e.g., 404 / Not Found, and 500 / Internal Server Error) isHttpError reflected in attributes instead isNetworkError properties.

public float downloadProgress;

Returns the floating point value between 0.0 and 1.0, indicating the progress of the text data is downloaded from the server. (Read Only)

Note : Only when a response server contains Content-Length header and UnityWebRequest have additional attributes to downloadHandler DownloadHandler, this property is effective.

If UnityWebRequest has completed (successfully or system error), then this property will always return 1. If UnityWebRequest still communicate with a remote server, and downloadHandler is null, this property will return 0.5. If Send has not been called, this property will return -1.

public float uploadProgress;

Returns the floating point value between 0.0 and 1.0, indicating the progress data is uploaded to the server.

If UnityWebRequest completed (successfully or system error), then this property will always return 1. If UnityWebRequest still communicate with a remote server, and uploadHandler is null, this property will return zero. If Send has not been called, this property will return -1.

public string error;

A readable string, describe any system errors UnityWebRequest this object is encountered while processing HTTP request or response. (Read Only)

If the system error UnityWebRequest not met, then this property will return null. System error examples include a socket error, parse redirection or limit error exceeds a DNS entry.

Note : the type of error return code from the server (e.g., 404 / File Not Found or 500 / Internal Server Error) is not considered a system error.

Default value: null.

public bool isDone;

Returns true after completion UnityWebRequest communicating with a remote server. (Read Only)

When UnityWebRequest successfully completed or encountered a system error, this property will return true. DownloadHandler done before (if any) of all post download processing returns true in this property.

Guess you like

Origin www.cnblogs.com/Mr147/p/10983956.html