版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
通过剖析Unity发现: Unity中WWW的web请求方式其实都是通过UnityWebRequest来实现的
代码语言:javascript复制 private UnityWebRequest _uwr;
一.WWW的Get请求实现:
代码语言:javascript复制public WWW(string url)
{
_uwr = UnityWebRequest.Get(url);
_uwr.SendWebRequest();
}
二.WWW的Post请求实现:
1.WWWForm表单:
代码语言:javascript复制 public WWW(string url, WWWForm form)
{
_uwr = UnityWebRequest.Post(url, form);
_uwr.chunkedTransfer = false;
_uwr.SendWebRequest();
}
2.byte数组:
代码语言:javascript复制public WWW(string url, byte[] postData)
{
_uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
_uwr.chunkedTransfer = false;
UploadHandler formUploadHandler = new UploadHandlerRaw(postData);
formUploadHandler.contentType = "application/x-www-form-urlencoded";
_uwr.uploadHandler = formUploadHandler;
_uwr.downloadHandler = new DownloadHandlerBuffer();
_uwr.SendWebRequest();
}
代码语言:javascript复制 public WWW(string url, byte[] postData, Dictionary<string, string> headers)
{
var verb = postData == null ? UnityWebRequest.kHttpVerbGET : UnityWebRequest.kHttpVerbPOST;
_uwr = new UnityWebRequest(url, verb);
_uwr.chunkedTransfer = false;
UploadHandler formUploadHandler = new UploadHandlerRaw(postData);
formUploadHandler.contentType = "application/x-www-form-urlencoded";
_uwr.uploadHandler = formUploadHandler;
_uwr.downloadHandler = new DownloadHandlerBuffer();
foreach (var header in headers)
_uwr.SetRequestHeader(header.Key, header.Value);
_uwr.SendWebRequest();
}