三国卡牌客户端基础资源仓库
yyl
2026-03-28 25eb0e50d4e815efb16d1a9953beac6ea1c7cfc3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Cysharp.Threading.Tasks;
 
 
public class HttpBehaviour : MonoBehaviour
    {
 
        string url;
        string method;
        string content;
        string contentType;
 
        int totalRetryTimes = 3;
        Action<bool, string> callBack;
 
        bool getResult = false;
        float timeOut = 0f;
        CookieContainer cookie;
        HttpWebRequest request;
        bool ok = false;
        string message = string.Empty;
        public static int ConnectAllTimes = 0;
        static HttpBehaviour()
        {
            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidationCallback;
        }
 
        public static void Create(string _url, string _method, string _content, string _contentType, int _retry = 3, Action<bool, string> _result = null)
        {
            var carrier = new GameObject();
            GameObject.DontDestroyOnLoad(carrier);
            carrier.hideFlags = HideFlags.HideInHierarchy;
            var behaviour = carrier.AddComponent<HttpBehaviour>();
            behaviour.Begin(_url, _method, _content, _contentType, _retry, _result);
        }
 
        /// <summary>
        /// Create 的异步版本,使用 UnityWebRequest 实现,支持所有平台(含 WebGL)。
        /// </summary>
        public static async UniTask<(bool ok, string message)> CreateAsync(string _url, string _method, string _content, string _contentType, int _retry = 3, Action<bool, string> _result = null)
        {
            bool ok = false;
            string message = string.Empty;
 
            for (int attempt = 0; attempt <= _retry; attempt++)
            {
                UnityWebRequest www;
                if (_method == "POST")
                {
                    var bodyRaw = Encoding.UTF8.GetBytes(_content);
                    www = new UnityWebRequest(_url, "POST");
                    www.uploadHandler = new UploadHandlerRaw(bodyRaw);
                    www.downloadHandler = new DownloadHandlerBuffer();
                    www.SetRequestHeader("Content-Type", _contentType);
                }
                else
                {
                    www = UnityWebRequest.Get(_url);
                    www.SetRequestHeader("Content-Type", _contentType);
                }
 
                using (www)
                {
                    await www.SendWebRequest();
                    ok = www.result == UnityWebRequest.Result.Success;
                    message = ok ? www.downloadHandler.text : www.error;
                }
 
                if (ok)
                {
                    ConnectAllTimes = 0;
                    break;
                }
 
                ConnectAllTimes++;
                Debug.LogWarning($"[HttpBehaviour] CreateAsync failed (attempt {attempt + 1}/{_retry + 1}): {message} url={_url}");
            }
 
            _result?.Invoke(ok, message);
            return (ok, message);
        }
 
        void Begin(string _url, string _method, string _content, string _contentType, int _retry = 3, Action<bool, string> _result = null)
        {
            this.url = _url;
            this.method = _method;
            this.content = _content;
            this.contentType = _contentType;
            this.totalRetryTimes = _retry;
            this.callBack = _result;
            this.timeOut = Time.time + 5f;
 
            try
            {
                cookie = new CookieContainer();
                request = (HttpWebRequest)WebRequest.Create(_url);
                request.ServicePoint.Expect100Continue = false;
                request.Method = _method;
                request.ContentType = _contentType;
                request.CookieContainer = cookie;
                request.Timeout = 2000;
                request.ReadWriteTimeout = 2000;
                request.Proxy = null;
                request.KeepAlive = true;  //设置为true,部分请求节点大文件会有问题,在请求完成后手动Abort释放
            }
            catch (Exception ex)
            {
                if (request != null)
                {
                    request.Abort();
                }
 
                ok = false;
                message = ex.Message;
                getResult = true;
            }
 
            if (_method == "POST")
            {
                var data = Encoding.UTF8.GetBytes(_content);
                request.ContentLength = data.Length;
                try
                {
                    var stream = request.BeginGetRequestStream(GetRequestStreamCallback, null);
                }
                catch (System.Exception ex)
                {
                    if (request != null)
                    {
                        request.Abort();
                    }
                    ok = false;
                    message = ex.Message;
                    getResult = true;
                }
            }
            else
            {
                try
                {
                    request.BeginGetResponse(OnHttpWebResponse, null);
                }
                catch (System.Exception ex)
                {
                    if (request != null)
                    {
                        request.Abort();
                    }
                    ok = false;
                    message = ex.Message;
                    getResult = true;
                }
            }
 
        }
 
        private static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;
            }
 
            var acceptCertificate = true;
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable)
            {
                acceptCertificate = false;
            }
            else
            {
                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    acceptCertificate = false;
                }
 
                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    foreach (X509ChainStatus item in chain.ChainStatus)
                    {
                        if (item.Status != X509ChainStatusFlags.RevocationStatusUnknown &&
                            item.Status != X509ChainStatusFlags.OfflineRevocation)
                        {
                            break;
                        }
 
                        if (item.Status != X509ChainStatusFlags.NoError)
                        {
                            acceptCertificate = false;
                        }
                    }
                }
            }
 
            if (acceptCertificate == false)
            {
                acceptCertificate = true;
            }
 
            return acceptCertificate;
        }
 
        void Update()
        {
            if (Time.time > timeOut && !getResult)
            {
                if (request != null)
                {
                    request.Abort();
                }
                ok = false;
                message = "TimeOut";
                getResult = true;
            }
 
            if (getResult)
            {
                try
                {
                    Debug.LogFormat("Http 数据通信 {0},请求数据结果:{1},内容:{2}", this.url, ok, message);
                    if (ok)
                    {
                        ConnectAllTimes = 0;
                    }
                    else
                    {
                        ConnectAllTimes++;
                    }
                    if (callBack != null)
                    {
                        callBack(ok, message);
 
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex);
                }
                finally
                {
                    callBack = null;
                    request?.Abort();
                    Destroy(this.gameObject);
                }
 
            }
        }
 
        private void GetRequestStreamCallback(IAsyncResult ar)
        {
            Stream postStream;
            try
            {
                postStream = request.EndGetRequestStream(ar);
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                request.BeginGetResponse(OnHttpWebResponse, request);
            }
            catch (Exception ex)
            {
                if (request != null)
                {
                    request.Abort();
                }
                ok = false;
                message = ex.Message;
                getResult = true;
            }
        }
 
        private void OnHttpWebResponse(IAsyncResult _result)
        {
            HttpWebResponse response = null;
            try
            {
                response = request.EndGetResponse(_result) as HttpWebResponse;
                response.Cookies = cookie.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                response.Close();
                request.Abort();
                ok = true;
                message = retString;
            }
            catch (System.Exception ex)
            {
                if (response != null)
                {
                    response.Close();
                }
 
                if (request != null)
                {
                    request.Abort();
                }
                ok = false;
                message = ex.Message;
                getResult = true;
            }
            finally
            {
                getResult = true;
            }
        }
 
 
    }