UnityWebRequest sends Json data to the backend

In many cases we need to pass json data to the backend for use. Here are two solutions.

Option One:

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);
 }

In order to ensure that the front end sends data in Json format so that the back end can parse it normally, the Content-Type in the request header must be set to "application/json"

Option II:

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);
 }

Because UnityWebRequest.Post treats Content-Type as application/x-www-form-urlencoded by default, the string we pass in will be URLEncoded, so we can only manually create an uploadHandler to overwrite the original uploadHandler.

Guess you like

Origin blog.csdn.net/weixin_56130753/article/details/133271958