用UnityWebRequest请求网络
时间: 2023-11-27 16:53:06 浏览: 207
UnityWebRequest 是 Unity 引擎提供的一种用于发送网络请求的类,它支持多种协议,包括 HTTP、HTTPS、FTP、File 等。下面是一个简单的例子,演示如何使用 UnityWebRequest 发送一个 GET 请求:
```csharp
IEnumerator GetRequest(string url)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + webRequest.error);
}
else
{
Debug.Log("Response: " + webRequest.downloadHandler.text);
}
}
}
```
这里使用了 IEnumerator 和 yield 关键字,因为 UnityWebRequest 是异步执行的,需要使用协程来处理。
使用 UnityWebRequest 发送 POST 请求也很简单,只需要将上面的 GetRequest 方法修改为:
```csharp
IEnumerator PostRequest(string url, string data)
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(data);
using (UnityWebRequest webRequest = UnityWebRequest.Post(url, "POST"))
{
webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
webRequest.downloadHandler = new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + webRequest.error);
}
else
{
Debug.Log("Response: " + webRequest.downloadHandler.text);
}
}
}
```
这里使用了 UploadHandlerRaw 将请求体转换为 byte 数组,并设置了 Content-Type 为 application/json。同时使用 DownloadHandlerBuffer 接收服务器响应的数据。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![cs](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)