使用.NET HttpWebRequest调用API遇TlsException问题求助
解决Unity中HttpWebRequest请求OW API的TlsException问题
我懂你现在的困扰——用.NET的HttpWebRequest在Unity里请求OW API,结果栽在了TLS认证这一步,试了方案还没解决,又不想碰Unity自带的API对吧?咱们来一步步搞定这个问题。
核心原因:TLS协议版本不匹配
Unity默认使用的.NET运行时版本(尤其是旧的.NET 3.5)默认启用的TLS版本比较老(比如TLS 1.0/1.1),而像ow-api这类现代API服务器已经不再支持这些旧协议,只接受TLS 1.2或更高版本,这就是你遇到TlsException: The authentication or decryption has failed的主要原因。
解决方案步骤
1. 强制指定TLS 1.2/1.3协议
在创建HttpWebRequest之前,先设置ServicePointManager.SecurityProtocol,明确指定要使用的TLS版本。这一步是关键,很多人就是漏了这个。
代码示例:
// 启用TLS 1.2和1.3,覆盖默认的旧协议 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
2. 检查并修改Unity的.NET运行时设置
如果上面的代码里SecurityProtocolType.Tls12报错(提示找不到这个枚举值),那说明你的Unity项目还在用旧的.NET 3.5运行时:
- 打开Unity编辑器,依次点击
Edit -> Project Settings -> Player -> Other Settings -> Configuration - 把
Scripting Runtime Version改成.NET 4.x Equivalent - 重启Unity,这个设置才会生效
3. 临时处理证书验证(仅开发阶段)
有时候Unity的证书存储可能存在问题,导致无法正常验证服务器的SSL证书。你可以临时绕过证书验证(注意:生产环境绝对不能这么做,会有安全风险):
// 开发阶段临时跳过证书验证,生产环境请删除这行 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
完整可运行的示例代码
把上面的步骤整合起来,写一个异步请求的脚本(避免阻塞Unity主线程):
using System; using System.Net; using System.IO; using UnityEngine; public class OWAPIFetcher : MonoBehaviour { private void Start() { // 第一步:设置TLS版本 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; // 第二步:开发阶段临时绕过证书验证(生产环境移除) ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; // 创建请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://ow-api.com/v1/stats/pc/eu/Epzz-2845/profile"); request.Method = "GET"; request.UserAgent = "Unity-OW-API-Fetcher"; // 加上UserAgent,避免被服务器拦截 // 异步发送请求,防止阻塞主线程 request.BeginGetResponse(OnResponseReceived, request); } private void OnResponseReceived(IAsyncResult result) { HttpWebRequest request = (HttpWebRequest)result.AsyncState; try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result)) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string jsonData = reader.ReadToEnd(); Debug.Log("成功获取JSON数据:\n" + jsonData); // 这里可以添加JSON反序列化逻辑,比如用Newtonsoft.Json } } catch (WebException ex) { Debug.LogError("请求失败:" + ex.Message); if (ex.Response != null) { using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response) { Debug.LogError("错误状态码:" + errorResponse.StatusCode); } } } } }
额外注意事项
- 生产环境必须移除证书验证的回调,确保服务器的SSL证书能正常通过验证,否则会面临中间人攻击的风险。
- 加上
UserAgent头是为了避免一些服务器把无标识的请求当成爬虫拦截。 - 建议用异步请求,因为同步请求会阻塞Unity主线程,导致游戏卡顿。
内容的提问来源于stack exchange,提问作者Nanopl
相关产品推荐
相关产品推荐

