【Unity】WebRequest发送https报错Cert verify failed

WebRequest请求https会报Curl error 51: Cert verify failed: UNITYTLS_X509VERIFY_FLAG_CN_MISMATCH

在Unity Forum查到解决方法, 就是需要指定WebRequest.certificateHandler。

重写UnityEngine.Networking.CertificateHandler类的ValidateCertificate方法:

using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityGameFramework.Runtime;

public class WebRequestCert : UnityEngine.Networking.CertificateHandler
{
    protected override bool ValidateCertificate(byte[] certificateData)
    {
        //return base.ValidateCertificate(certificateData);
        return true;
    }
}

然后把WebRequest的certificateHandler设置为new WebRequestCert()

var content_bytes = System.Text.Encoding.UTF8.GetBytes(ObjectToJson(parms));
        var web_req = UnityEngine.Networking.UnityWebRequest.Post(url, string.Empty);
        web_req.uploadHandler = new UnityEngine.Networking.UploadHandlerRaw(content_bytes);
        web_req.SetRequestHeader("Content-Type", "application/json");
        web_req.certificateHandler = new WebRequestCert();
        web_req.timeout = 20;
        yield return web_req.SendWebRequest();

我这里把证书验证直接强制返回true了,肯定是不严谨的。至于证书验证这块该怎么实现我还不清楚,路过的大佬如果知道更好方式还请留言赐教

你可能感兴趣的:(Unity)