Unity: POST request using WWW class using JSON

后端 未结 4 1482
情话喂你
情话喂你 2021-01-07 01:18

I am trying to make a POST request to restful web APIs in Unity.

The header would be Content-Type: application/json

An example of the raw data i

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 01:40

    private void SendJson(string url, string json)
    {
        StartCoroutine(PostRequestCoroutine(url, json, callback));
    }
    
    private IEnumerator PostRequestCoroutine(string url, string json)
    {
        var jsonBinary = System.Text.Encoding.UTF8.GetBytes(json);    
    
        DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();
    
        UploadHandlerRaw uploadHandlerRaw = new UploadHandlerRaw(jsonBinary);
        uploadHandlerRaw.contentType = "application/json";
    
        UnityWebRequest www = 
            new UnityWebRequest(url, "POST", downloadHandlerBuffer, uploadHandlerRaw);
    
        yield return www.SendWebRequest();
    
        if (www.isNetworkError)
            Debug.LogError(string.Format("{0}: {1}", www.url, www.error));
        else
           Debug.Log(string.Format("Response: {0}", www.downloadHandler.text));
    }
    

提交回复
热议问题