使用UnityWebRequest,发送一个post请求,请求头添加:"Auorizontionl":"46asf465f48af54ds21x",请求body添加"username":"xuyu",将请求返回的数据解析为json
时间: 2023-06-10 15:04:28 浏览: 128
好的,您想了解如何使用UnityWebRequest发送请求、添加请求头和请求体,以及如何解析返回的数据为json格式。以下是代码示例:
```c#
using UnityEngine;
using UnityEngine.Networking;
using SimpleJSON;
public class RequestManager : MonoBehaviour
{
void Start()
{
StartCoroutine(SendPostRequest());
}
IEnumerator SendPostRequest()
{
string url = "http://example.com/api/user";
string bodyJsonString = "{\"username\":\"xuyu\"}";
UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "46asf465f48af54ds21x");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
string responseJsonString = request.downloadHandler.text;
JSONNode data = JSON.Parse(responseJsonString);
Debug.Log("Response: " + data.ToString());
}
else
{
Debug.LogError("Request error: " + request.error);
}
}
}
```
此代码会向`http://example.com/api/user` 发送一个post请求,请求头包括:"Authorization":"46asf465f48af54ds21x",请求体包括:"username":"xuyu"。请求成功后,返回的数据将被解析为json格式并打印在console中。
希望这能帮到您。
阅读全文