Unity common network request method

Primer

The editor has been testing the API interface for the past two days, mainly using the programs written on Postman and Unity for testing, just to share with you the commonly used network request methods in Unity

Unity Network Requestor Walkthrough

UnityWebRequest

UnityWebRequest is a new API introduced by Unity 5.2, which can be used to make network requests of HTTP, HTTPS, FTP and other protocols. It supports asynchronous requests and supports GET, POST and other request methods. UnityWebRequest can handle most common HTTP status response codes, such as 404 (Not Found), 302 (Redirect), 500 (Internal Server Error), etc. UnityWebRequest also supports uploading and downloading files, and running requests in the background

GET request

Here is an example of sending a GET request using UnityWebRequest:

IEnumerator GetRequest(string url)
{
    UnityWebRequest request = UnityWebRequest.Get(url);

    yield return request.SendWebRequest();

    if (request.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(request.error);
    }
    else
    {
        Debug.Log(request.downloadHandler.text);
    }
}
 

You can add this function to the MonoBehaviour script and call it when needed. For example:

void Start()
{
    string url = "https://jsonplaceholder.typicode.com/todos/1";
    StartCoroutine(GetRequest(url));
}

POST request

The following is a sample code for sending a POST request using UnityWebRequest:

string url = "http://example.com/api/user/login";
string data = "{\"username\":\"test\",\"password\":\"123456\"}";

UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(data);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");

yield return request.SendWebRequest();

if (request.result == UnityWebRequest.Result.Success)
{
    string responseText = request.downloadHandler.text;
    // 处理服务器返回的数据
}
else
{
    Debug.LogError(request.error);
}

In the above example, we used the UnityWebRequest object to initiate a POST request. We first define the URL of the request target and the data of the request body. Next, create an object of UnityWebRequest type, specify the request method as POST, set the request body, and specify the request header. Then  SendWebRequest send the request through the method. After the request is sent successfully, we can  downloadHandler get the server's response data from the attribute and process it accordingly. If the request fails to be sent,  error the error information can be obtained from the property.

WWW

WWW is the network request class used by earlier versions of Unity 3D. It is easy to use and can be used to load resources such as pictures, audio, video, etc., and can also be used to make HTTP requests. However, the WWW class is not as powerful as UnityWebRequest, it does not handle HTTP status response codes well, nor does it support uploading and downloading files

GET request

Here is an example of a simple Unity WWW Get request:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

    void Start () {
        StartCoroutine(GetText());
    }

    IEnumerator GetText() {
        // 向http://www.example.com发送GET请求
        using (WWW www = new WWW("http://www.example.com")) {
            yield return www; // 等待请求完成

            // 检查是否有错误
            if (string.IsNullOrEmpty(www.error)) {
                Debug.Log("Response: " + www.text);
            } else {
                Debug.Log("Error: " + www.error);
            }
        }
    }
}

In this example, we http://www.example.comsend a GET request to and wait for it to complete. Once the request is complete, we check for errors and output the text returned by the server. Note that we used a coroutine because the WWW request is asynchronous in Unity, so we need to wait for it to complete

POST request

Here is a sample code for sending a POST request using Unity:

IEnumerator Post(string url, string data)
{
    // 将数据转换为字节数组
    byte[] postData = Encoding.UTF8.GetBytes(data);

    // 创建一个Web请求
    UnityWebRequest request = UnityWebRequest.Post(url, "POST");

    // 设置请求体中的数据
    request.uploadHandler = new UploadHandlerRaw(postData);

    // 设置请求头中的内容类型
    request.SetRequestHeader("Content-Type", "application/json");

    // 发送请求
    yield return request.SendWebRequest();

    // 检查请求是否发生错误
    if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
    {
        Debug.Log("POST请求错误:" + request.error);
    }
    else
    {
        // 获取响应数据
        string response = request.downloadHandler.text;

        // 处理响应数据
        Debug.Log("POST请求响应:" + response);
    }
}

Example usage:

StartCoroutine(Post("https://httpbin.org/post", "{\"name\": \"test\"}"));

This example will send a POST request to the https://httpbin.org/post URL and carry a JSON data named test. You can modify the url and data parameters as needed to send different requests.

HttpClient

HttpClient is a .NET Http programming library that can be used to make network requests in Unity. It supports asynchronous requests and supports GET, POST and other request methods. However, HttpClient is a standalone .NET library and needs to be manually imported into the project

GET request

The following is a sample code that uses the HttpClient class in C# to initiate a GET request:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient();
        // 设置请求头信息,可选
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        try
        {
            // 发起GET请求
            var response = await client.GetAsync("https://www.example.com/");
            response.EnsureSuccessStatusCode(); // 确保响应成功
            var responseBody = await response.Content.ReadAsStringAsync(); // 获取响应主体内容
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"请求失败:{e.Message}");
        }
    }
}

This example uses a method HttpClientin the class GetAsyncto make a GET request and EnsureSuccessStatusCodea method to ensure a successful response. The body content of the response can ReadAsStringAsyncbe obtained using the method. Before the request, you can use DefaultRequestHeadersattributes to set the request header information, or you can pass the object as a parameter when sending the request HttpHeaders.

POST request

Here's an example of a POST request using HttpClient in Unity:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class HttpClientExample : MonoBehaviour {
    async void Start() {
        var values = new Dictionary<string, string> {
            { "username", "example_user" },
            { "password", "example_password" }
        };

        var content = new FormUrlEncodedContent(values);

        using (var client = new HttpClient()) {
            var response = await client.PostAsync("http://example.com/api/login", content);

            var responseString = await response.Content.ReadAsStringAsync();

            var responseData = JsonConvert.DeserializeObject<LoginResponse>(responseString);
            
            Debug.Log("Login Status: " + responseData.success);
            Debug.Log("User ID: " + responseData.user_id);
        }
    }
}

public class LoginResponse {
    public bool success { get; set; }
    public string user_id { get; set; }
}

In this example, we create a Dictionary object to store the parameters of the POST request, then use FormUrlEncodedContent to convert it into content that can be sent to the server. We send a POST request to the "http://example.com/api/login" address and use HttpClient to handle the response. Finally, we use JsonConvert to deserialize the response data into a LoginResponse object and output it to Unity's console.

Note that since HttpClient is asynchronous, we must use the async and await keywords when using it. This will ensure that our application does not hang while waiting for a response.

RESTful API

It is an API interface based on the HTTP protocol, which uses HTTP methods such as POST, GET, DELETE, and PUT to operate resources. In Unity, you can use libraries such as UnityWebRequest and HttpClient to call the RESTful API interface

GET request

Here is a sample code for a basic GET request using RESTful API in Unity:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

public class RESTfulAPIExample : MonoBehaviour {
    IEnumerator Start() {
        // 设置请求的url
        string url = "http://www.example.com/api/data";

        // 创建GET请求对象
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/json";

        // 发送请求并获取响应信息
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        string result = reader.ReadToEnd();
        reader.Close();
        response.Close();

        // 处理响应数据
        Debug.Log(result);

        yield return null;
    }
}

The above code snippet uses Unity's coroutine function to send a GET request to the specified url (ie http://www.example.com/api/data), and obtains the data from the response and prints it to the console. This request uses the Content-Type header of application/json. If you need to use other types of Content-Type, you need to modify it accordingly.

It should be noted that the requests in the above code are all synchronous requests. If you need to use asynchronous requests or other more advanced functions, you need to make corresponding extensions and modifications.

POST request

Here is an example of C# code using Unity to send a POST request to a RESTful API:

IEnumerator PostRequest(string url, string jsonData)
{
    UnityWebRequest request = UnityWebRequest.Post(url, "POST");
    byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
    request.uploadHandler = new UploadHandlerRaw(bodyRaw);
    request.downloadHandler = new DownloadHandlerBuffer();

    yield return request.SendWebRequest();

    if (request.result == UnityWebRequest.Result.ConnectionError || 
        request.result == UnityWebRequest.Result.ProtocolError)
    {
        Debug.LogError(request.error);
    }
    else
    {
        Debug.Log(request.downloadHandler.text);
    }
}

The parameter in the example  url is the target URL of the POST request, and  jsonData the parameter is the JSON data to be sent.

The code uses Unity's  UnityWebRequest class to send a POST request. UnityWebRequest Allows you to specify the type of request ("POST" in this case), upload the request body, and download the response body from the response.

Use  yield the keyword to make this function a coroutine to ensure that requests are executed on a background thread without blocking the main thread. After the coroutine completes, check the result of the UnityWebRequest object for errors, and output the text content of the response or an error message.

Socket

Suitable for custom network protocols, which can realize customized network communication

GET request

Here is an example of a simple Unity C# Socket GET request:

using System;
using System.Net.Sockets;
using System.Text;

public class SocketGETRequest {
    public static void Main() {
        // 创建一个Socket对象
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // 连接到目标网站
        clientSocket.Connect("www.example.com", 80);

        // 构建HTTP GET请求
        string getRequest = "GET / HTTP/1.1\r\n";
        getRequest += "Host: www.example.com\r\n";
        getRequest += "Connection: Close\r\n\r\n";

        // 发送请求
        byte[] requestBytes = Encoding.ASCII.GetBytes(getRequest);
        clientSocket.Send(requestBytes);

        // 接收响应
        byte[] buffer = new byte[1024];
        int bytesRead = clientSocket.Receive(buffer);
        string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);

        // 输出响应
        Console.WriteLine(response);

        // 关闭Socket连接
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
    }
}

In this example, we create a Socket object, connect to a website named www.example.com, then construct an HTTP GET request, send the request to the server, and wait for a response. Finally, we output the response and close the Socket connection.

POST request

The following is an example of using Unity's C# code sample to make a Socket POST request:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SocketClient
{
    private Socket socket;

    public SocketClient()
    {
        try
        {
            // 创建Socket
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        catch (SocketException ex)
        {
            Debug.Log($"创建Socket失败: {ex}");
        }
    }

    public void Request(string url, string data)
    {
        try
        {
            // 解析URL
            Uri uri = new Uri(url);
            IPAddress ipAddress = Dns.GetHostAddresses(uri.Host)[0];
            IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, uri.Port);

            // 连接服务器
            socket.Connect(remoteEndPoint);

            // 构造HTTP POST请求
            string request = $"POST {uri.PathAndQuery} HTTP/1.1\r\n" +
                             $"Host: {uri.Host}\r\n" +
                             "Content-Type: application/x-www-form-urlencoded\r\n" +
                             $"Content-Length: {data.Length}\r\n" +
                             "Connection: close\r\n" +
                             "\r\n" +
                             $"{data}";

            // 发送请求
            byte[] requestBytes = Encoding.ASCII.GetBytes(request);
            socket.Send(requestBytes);

            // 接收服务器响应
            byte[] receiveBuffer = new byte[1024];
            int receiveSize = socket.Receive(receiveBuffer);

            // 处理服务器响应
            string response = Encoding.ASCII.GetString(receiveBuffer, 0, receiveSize);
            Debug.Log($"服务器响应:{response}");
        }
        catch (Exception ex)
        {
            Debug.Log($"请求异常:{ex}");
        }
        finally
        {
            // 关闭连接
            socket.Close();
        }
    }
}

Example usage:

SocketClient socketClient = new SocketClient();
socketClient.Request("http://localhost:8080/your_api_path", "param=value");

Note: The above examples are only used to demonstrate the basic process of Socket POST requests, and more security issues such as exception handling and data encryption need to be considered in practical applications.

Summarize

In the process of using network requests, you need to pay attention to the selection of request methods, the setting of request parameters, and the processing of request results. At the same time, it is also necessary to pay attention to possible errors during the network request process, such as network connection failure, request timeout, server return error, etc., and reasonable exception handling is required

If you have any questions, you can add me to chat with WeChat at yf1553653788

Guess you like

Origin blog.csdn.net/Ai1114/article/details/132344226