什么是UnityWebRequest
Unity库中提供了基本的HTTP请求库,这个库可以做到跨平台,并且封装了AssetBundle、Texture等常用加载资源的方法。
UnityWebRequest提供了两套API,一类叫做HL API(高级API),一类叫做LL API (低级API)。
HLAPI意思是开发者可以直接调用Get、Post请求。
LLAPI意思是开发者需要手动写UploadHandler、DownloadHandler。
使用UnityWebRequest
- www是旧版用法
- 判断请求是否成功,使用
req.result == UnityWebRequest.Result.Success
GET请求
UnityWebRequest req = new UnityWebRequest($"https://baidu.com");
//绕过SSL证书验证
req.certificateHandler = new BypassCertificate();
req.downloadHandler = new DownloadHandlerBuffer();
var asyncOp = req.SendWebRequest();
while (asyncOp.isDone == false)
{
await Task.Delay(1000 / 30); //30 hertz
}
var s = req.downloadHandler.text;
POST请求
internal class BypassCertificate : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
return true;
}
}
[Test]
public static void testRequest()
{
var url = "https://weiyinfu.cn/jiahe/";
UnityWebRequest req = new UnityWebRequest(url);
//绕过SSL证书验证
req.certificateHandler = new BypassCertificate();
req.downloadHandler = new DownloadHandlerBuffer();
req.method = "POST";
req.SetRequestHeader("Content-Type", "application/json");
var data = new JObject();
data["content"] = "hello";
Debug.Log(data.ToString());
var d = Encoding.UTF8.GetBytes(data.ToString());
req.uploadHandler = new UploadHandlerRaw(d);
var asyncOp = req.SendWebRequest();
while (asyncOp.isDone == false)
{
Thread.Sleep(300);
// await Task.Delay(1000 / 30); //30 hertz
}
var s = req.downloadHandler.text;
Debug.Log(s);
}
C#的HttpClient
public static void testHttpClient()
{
HttpClient cli = new HttpClient();
var data = new JObject();
data["content"] = "hello";
Debug.Log(data.ToString());
var content = new StringContent(data.ToString(), Encoding.UTF8);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var resp = cli.PostAsync("https://weiyinfu.cn/jiahe/", content);
resp.Wait();
var sTask = resp.Result.Content.ReadAsStringAsync();
sTask.Wait();
var s = sTask.Result;
Debug.Log($"result= {s}");
}
Unity WebRequest特点
- https的端口号默认也是80端口,因此在URL中必须指明端口号
- 下面这种发送方式,ContentType默认是:
*application/x-www-form-urlencoded*
JObject obj = new JObject();
obj["content"] = DateTime.Now.ToString();
var ss = JsonConvert.SerializeObject(obj);
UnityWebRequest www = UnityWebRequest.Post("http://localhost:9001/why", ss);
排查simpleget为啥请求80端口。
- 端口号最好带着,即便是https接口也要带着端口号,因为有一些http库并不会实现https就请求443端口。
- 请求路径长一点,如果是请求weiyinfu.cn/jiahe则会进行301重定向,就变成了get请求。所以应该是weiyinfu.cn/jiahe/