使用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}");
}