Unity使用UnityWebRequest发送HTTP请求并处理返回结果

场景:公司最近项目需要对接http的后台服务器后发送请求并处理其返回结果,在使用WWW时发现新版本已经对该API弃用,于是使用unity新版的api:UnityWebRequest进行发送http协议的请求。

遇到的问题:在使用UnityWebRequest.POST进行请求时,HTTP服务器那边总是会返回HTTP/1.1 500 Internal Server Error的错误,后来跟后台沟通后发现UnityWebRequest.POST使用的默认的请求头(也就是Content_Type)不对导致的。于是需要手动设置跟服务器一致的请求头,具体代码如下:

    public void Post(string _postData)
    {
        StartCoroutine(PostRequest(_postData));
    }

    private IEnumerator PostRequest(string _postData)
    {
        using (UnityWebRequest webRequest = new UnityWebRequest(m_url, UnityWebRequest.kHttpVerbPOST))
        {
            UploadHandler uploader = new UploadHandlerRaw(System.Text.Encoding.Default.GetBytes(_postData));
            webRequest.uploadHandler = uploader;
            webRequest.uploadHandler.contentType = "application/json";  //设置HTTP协议的请求头,默认的请求头HTTP服务器无法识别

            //这里需要创建新的对象用于存储请求并响应后返回的消息体,否则报空引用的错误
            DownloadHandler downloadHandler = new DownloadHandlerBuffer();
            webRequest.downloadHandler = downloadHandler;

            //Debug.Log(webRequest.uploadHandler.data.Length);

            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.LogError(webRequest.error + webRequest.isHttpError);
            }
            else
            {
                //string reciveStr = System.Text.Encoding.UTF8.GetString(webRequest.downloadedBytes);
                Debug.Log("Form upload complete And receive data :" + webRequest.downloadHandler.text);
            }
        }
    }

注意:

_postData参数为json格式的字符串

你可能感兴趣的:(Unity,API)