UnityWebRequest usage

1: Unity network tools:

Unity originally had a tool class WWW accessed by Http. In the new version of unity, a new tool class UnityWebRequest was introduced to replace the original WWW class. After that, we try to use UnityWebRequest to make a request.

2: Simple Get access

UnityWebRequest contains multiple static methods. You can create a UnityWebRequest object and call SendWebRequest to formally send the request. After the result is returned from the collaboration process, you need to judge whether there is an error before processing.

    IEnumerator GetText()
    {
        //Just use the Get method directly
        UnityWebRequest www = UnityWebRequest.Get("http://127.0.0.1:9997/gameInit?uid=7");
        //Set request timeout
        www.timeout = 5;
        //send, the request starts to execute
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            // Show results as text
            Debug.Log(www.downloadHandler.text); 
            // Or retrieve results as binary data
            byte[] results = www.downloadHandler.data;
        }
    }

3: Http post access

The data submitted by post access in the project is in json format. Here, we need to process the submitted data uploadHandler and replace the submitted data with byte array.
   

 public IEnumerator PostRequest(string url, string jsonString, Action<string> callback)

    {

        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))

        {

            byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonString);

            webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);

            webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();


            yield return webRequest.SendWebRequest();


            if (webRequest.isHttpError || webRequest.isNetworkError)

            {

                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);

                if (callback != null)

                {

                    callback(null);

                }

            }

            else

            {

                if (callback != null)

                {

                    callback(webRequest.downloadHandler.text);

                }

            }

        }

 }

It can be called directly from the outside. In essence, it is to initialize a WebRequest, and then set the corresponding upload and download handlers. Finally, request completion and call the corresponding delegate

 

4: Download AssetBundle

    IEnumerator GetAssetBundle() {

        const string url1 = @"http://127.0.0.1:8080/mat";     

        const string url2 = @"http://127.0.0.1:8080/image";

        UnityWebRequest request1 = UnityWebRequestAssetBundle.GetAssetBundle(url1); / / Unity network requests AssetBundle Get resources (network address 1)

        UnityWebRequest request2 = UnityWebRequestAssetBundle.GetAssetBundle(url2); / / incoming address 2

        yield return request1.SendWebRequest(); / / send Web request 1

        yield return request2.SendWebRequest(); / / send web request 2

        AssetBundle ab1 = DownloadHandlerAssetBundle.GetContent(request1); / / download resources, obtain connection request 1, and return AssetBundle resources

        AssetBundle ab2 = DownloadHandlerAssetBundle.GetContent(request2); / / obtain connection request 2 and return AssetBundle resource

/ / obtain AsseBundle resources, and then you can do anything

}

 

5: Receive Texture

You can use unitywebrequesttexture GetTexture method to obtain a texture file from the remote server. This function is similar to unitywebrequest The get method is very similar, but it optimizes the downloading and storage of texture files and improves the processing efficiency. UnityWebRequest.Texture also needs a string parameter, which is the URL address of the resource to be downloaded.

    IEnumerator GetTexture()
    {
        //Directly encapsulate the function of downloading pictures, and there is no need to talk about byte conversion into pictures. DownloadHandlerTexture is automatically bound inside this class
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(
            "http://127.0.0.1:9999/BidCardBorder.png");
        yield return www.SendWebRequest();
        if (www.isHttpError || www.isNetworkError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
            this.GetComponent<MeshRenderer>().material.mainTexture = myTexture;
        }
    }

6: Post key value pair mode request

Sometimes, when passing parameters, we use the key value method. The code is as follows

IEnumerator PostKeyValue()
    {
        WWWForm form = new WWWForm();
        //Key value pair
        form.AddField("name", "zhangsan");
        form.AddField("password", "123456");
        //Request the link and send the form object to the remote server
        UnityWebRequest webRequest = UnityWebRequest.Post("http://127.0.0.1:8080/login", form);

        yield return webRequest.SendWebRequest();
        if (webRequest.isHttpError || webRequest.isNetworkError)
        {
            Debug.Log(webRequest.error);
        }
        else
        {
            Debug.Log("Successfully sent");
        }
    }

 

7: Comparison of two common Get requests

Use the unitywebrequest provided by the system During get, the DownloadHandler has been bound for us by default. We don't need to set it ourselves. When we use ourselves, we must make corresponding settings. The code is as follows:

    IEnumerator SendRequest()
    {
        Uri uri = new Uri("http://127.0.0.1:9997/gameInit?uid=7");
        //1: Create UnityWebRequest object
        UnityWebRequest uwr = new UnityWebRequest(uri);
        uwr.method = "GET";
        uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

        //2: Create a UnityWebRequest object, which is equivalent to the above
        //  UnityWebRequest uwr = UnityWebRequest.Get("http://127.0.0.1:9997/gameInit?uid=7"); 
        uwr.timeout = 5;
        //Set request timeout

        yield return uwr.SendWebRequest();                     //Waiting for the requested information to be returned
        if (uwr.isHttpError || uwr.isNetworkError)             //If its request fails or a network error occurs
        {
            Debug.LogError(uwr.error); //Print error reason
        }
        else //Request succeeded
        {
            Debug.Log("Request succeeded");
            //Download data using DownloadHandler
            Debug.Log(uwr.downloadHandler.text);
            //Just parse the corresponding Json data
        }
    }

 

Keywords: Unity3d

Added by praxedis on Thu, 17 Feb 2022 21:59:51 +0200