在很多时候我们需要把json数据传递给后端使用,这里提供两种方案。
方案一:
private void Start()
{
string url="xxx";
string json="一个Json格式的数据,这里大家替换成自己想要测试的Json数据";
StartCoroutine(I_RequestByJsonBodyPost(url,json));
}
private static IEnumerator I_RequestByJsonBodyPost(string url, string json)
{
UnityWebRequest www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
DownloadHandler downloadHandler = new DownloadHandlerBuffer();
www.downloadHandler = downloadHandler;
www.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
yield return www.SendWebRequest();
Debug.Log(www.downloadHandler.text);
}
为了保证前端发送的是 Json 格式的数据,让后端能够正常地解析,必须要把请求头中的 Content-Type 设为 “application/json”
方案二:
private void Start()
{
string url="xxx";
string json="一个Json格式的数据,这里大家替换成自己想要测试的Json数据";
StartCoroutine(I_RequestByJsonBodyPost(url,json));
}
private static IEnumerator I_RequestByJsonBodyPost(string url, string json)
{
UnityWebRequest www = UnityWebRequest.Post(url, json);
www.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
yield return www.SendWebRequest();
Debug.Log(www.downloadHandler.text);
}
因为 UnityWebRequest.Post 默认把 Content-Type 当作 application/x-www-form-urlencoded,所以我们传进去的字符串会被 URLEncoded,因此只能手动创建一个 uploadHandler,覆盖掉原来的 uploadHandler。