当前位置:   article > 正文

BestHttp插件

besthttp

Unity商店有一款评分很高的网络通信插件BestHttp。笔者做了一些简单测试。官方地址:https://assetstore.unity.com/packages/tools/network/best-http-2-155981

Demo工程及插件,会在文章末尾提供。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using BestHTTP;
  5. using BestHTTP.Authentication;
  6. using BestHTTP.Cookies;
  7. using System;
  8. using System.Text;
  9. using System.IO;
  10. using Org.BouncyCastle.Crypto.Tls;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  12. using BestHTTP.Statistics;
  13. using BestHTTP.WebSocket;
  14. using BestHTTP.WebSocket.Frames;
  15. using BestHTTP.SocketIO;
  16. using BestHTTP.SignalR;
  17. /*
  18. * Author:W
  19. * Http协议处理
  20. */
  21. /// <summary>
  22. /// 实现服务器证书验证接口
  23. /// </summary>
  24. public class CustomVerifier : ICertificateVerifyer
  25. {
  26. public bool IsValid(Uri serverUri, X509CertificateStructure[] certs)
  27. {
  28. // TODO: Return false, if validation fails
  29. return true;
  30. }
  31. }
  32. public delegate void OnServerCallBack(Socket socket, Packet originalPacket, params object[] args);
  33. public class HttpTest : MonoBehaviour {
  34. private HTTPRequest request1;
  35. /// <summary>
  36. /// 大文件流式请求,下载的文件存放到某一个文件目录下
  37. /// </summary>
  38. private HTTPRequest streamReq;
  39. /// <summary>
  40. /// 大文件上传请求
  41. /// </summary>
  42. private HTTPRequest upStreamReq;
  43. /// <summary>
  44. /// 支持服务器主动向客户端推送消息
  45. /// </summary>
  46. private WebSocket webSocket;
  47. /// <summary>
  48. /// SocketIO管理对象
  49. /// </summary>
  50. private SocketManager socketManager;
  51. /// <summary>
  52. /// singalR通信对象
  53. /// </summary>
  54. private Connection singalRConnect;
  55. #region 一般Http请求,TCP连接
  56. /// <summary>
  57. /// Get请求:向特定的资源发出请求。
  58. /// </summary>
  59. /// <param name="url"></param>
  60. public HTTPRequest GetRequest(string url)
  61. {
  62. HTTPRequest request = new HTTPRequest(new Uri(url), OnRequestFinished);
  63. request.Send();
  64. return request;
  65. }
  66. /// <summary>
  67. /// Post请求:向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。
  68. /// 数据被包含在请求体中。POST请求可能会导致新的资源的创建或已有资源的修改。
  69. /// </summary>
  70. /// <param name="url"></param>
  71. public HTTPRequest PostRequest(string url,Dictionary<string,string> paramDict = null)
  72. {
  73. HTTPRequest request = new HTTPRequest(new Uri(url),HTTPMethods.Post, OnRequestFinished);
  74. if (paramDict != null && paramDict.Count != 0)
  75. {
  76. foreach (KeyValuePair<string,string> v in paramDict)
  77. {
  78. request.AddField(v.Key, v.Value);
  79. }
  80. }
  81. request.Send();
  82. return request;
  83. }
  84. /// <summary>
  85. /// Head请求:向服务器索要与GET请求相一致的响应,只不过响应体将不会被返回。
  86. /// 这一方法可以在不必传输整个响应内容的情况下,就可以获取包含在响应消息头中的元信息。
  87. /// </summary>
  88. /// <param name="url"></param>
  89. public HTTPRequest HeadPost(string url)
  90. {
  91. HTTPRequest request = new HTTPRequest(new Uri(url),HTTPMethods.Head,OnRequestFinished);
  92. request.Send();
  93. return request;
  94. }
  95. /// <summary>
  96. /// Put请求:向指定资源位置上传其最新内容。
  97. /// </summary>
  98. /// <param name="url"></param>
  99. public HTTPRequest PutRequest(string url)
  100. {
  101. HTTPRequest request = new HTTPRequest(new Uri(url),HTTPMethods.Put,OnRequestFinished);
  102. request.Send();
  103. return request;
  104. }
  105. /// <summary>
  106. /// Delete请求:请求服务器删除 Request-URI 所标识的资源。
  107. /// </summary>
  108. /// <param name="url"></param>
  109. public HTTPRequest DeleteRequest(string url)
  110. {
  111. HTTPRequest request = new HTTPRequest(new Uri(url),HTTPMethods.Delete,OnRequestFinished);
  112. request.Send();
  113. return request;
  114. }
  115. /// <summary>
  116. /// Patch请求:是对 PUT 方法的补充,用来对已知资源进行局部更新 。
  117. /// </summary>
  118. /// <param name="url"></param>
  119. public HTTPRequest PatchRequest(string url)
  120. {
  121. HTTPRequest request = new HTTPRequest(new Uri(url),HTTPMethods.Patch,OnRequestFinished);
  122. request.Send();
  123. return request;
  124. }
  125. private void OnRequestFinished(HTTPRequest request, HTTPResponse response)
  126. {
  127. Debug.Log("Get 请求结果==" + response.DataAsText);
  128. if (response.StatusCode != 401)
  129. {
  130. Debug.Log("校验通过的");
  131. }
  132. else
  133. {
  134. Debug.Log("校验没通过的");
  135. }
  136. }
  137. #endregion
  138. #region 大文件Http请求
  139. private HTTPRequest StreamRequest(string url)
  140. {
  141. HTTPRequest request = new HTTPRequest(new Uri(url), OnStreamRequestFinished);
  142. //开启流式文件请求
  143. request.UseStreaming = true;
  144. request.StreamFragmentSize = 1 * 1024 * 1024;//1M
  145. //关闭缓存,因为已经将请求回来的数据保存到文件中
  146. request.DisableCache = true;
  147. request.Send();
  148. return request;
  149. }
  150. /// <summary>
  151. /// 大文件流式请求响应处理
  152. /// </summary>
  153. /// <param name="request"></param>
  154. /// <param name="response"></param>
  155. private void OnStreamRequestFinished(HTTPRequest request, HTTPResponse response)
  156. {
  157. List<byte[]> fragments = response.GetStreamedFragments();
  158. //下载的数据保存到文件中
  159. using (FileStream fs = new FileStream("pathToSave", FileMode.Append))
  160. {
  161. foreach (byte[] data in fragments)
  162. {
  163. fs.Write(data,0,data.Length);
  164. }
  165. }
  166. if (response.IsStreamingFinished)
  167. Debug.Log("大文件下载完毕!");
  168. }
  169. #endregion
  170. #region 大文件上传Http请求
  171. /// <summary>
  172. /// 大文件上传请求
  173. /// </summary>
  174. /// <param name="url"></param>
  175. /// <returns></returns>
  176. private HTTPRequest UpStreamRequest(string url)
  177. {
  178. HTTPRequest request = new HTTPRequest(new Uri(url),HTTPMethods.Post, OnUploadFinished);
  179. request.UploadStream = new FileStream("File_To.Upload",FileMode.Open);
  180. request.OnUploadProgress = OnUploadProgress;
  181. request.Send();
  182. return request;
  183. }
  184. /// <summary>
  185. /// 上传结束处理
  186. /// </summary>
  187. /// <param name="request"></param>
  188. /// <param name="response"></param>
  189. private void OnUploadFinished(HTTPRequest request, HTTPResponse response)
  190. {
  191. Debug.Log("文件上传结束!");
  192. }
  193. /// <summary>
  194. /// 上传进度回调
  195. /// </summary>
  196. /// <param name="request"></param>
  197. /// <param name="uploaded"></param>
  198. /// <param name="length"></param>
  199. private void OnUploadProgress(HTTPRequest request, long uploaded, long length)
  200. {
  201. float progressPercent = (uploaded / (float)length) * 100.0f;
  202. Debug.Log("文件上传进度: " + progressPercent.ToString("F2") + "%");
  203. }
  204. #endregion
  205. #region WebSocket
  206. /// <summary>
  207. /// WebSocket使用
  208. /// 一种双向通信协议,也是建立在TCP之上。
  209. /// </summary>
  210. /// <param name="url"></param>
  211. private void SetWebSocket(string url)
  212. {
  213. webSocket = new WebSocket(new Uri(url));
  214. webSocket.OnOpen += OnWebSocketOpen;
  215. webSocket.OnMessage += OnMessageReceived;
  216. webSocket.OnBinary += OnBinaryMessageReceived;
  217. webSocket.OnClosed += OnWebSocketClosed;
  218. webSocket.OnError += OnError;
  219. webSocket.OnErrorDesc += OnErrorDesc;
  220. webSocket.OnIncompleteFrame += OnIncompleteFrame;
  221. webSocket.Open();
  222. webSocket.Send("I am Winner!");
  223. byte[] buffer = new byte[1024];
  224. webSocket.Send(buffer);
  225. //webSocket.Close();
  226. }
  227. /// <summary>
  228. /// 连接建立的时候
  229. /// </summary>
  230. /// <param name="webSocket"></param>
  231. private void OnWebSocketOpen(WebSocket webSocket)
  232. {
  233. Debug.Log("WebSocket 打开!");
  234. }
  235. /// <summary>
  236. /// 接收服务器推送过来的消息
  237. /// </summary>
  238. /// <param name="webSocket"></param>
  239. /// <param name="message"></param>
  240. private void OnMessageReceived(WebSocket webSocket, string message)
  241. {
  242. Debug.Log("接收服务器推送过来的消息字符串: " + message);
  243. }
  244. /// <summary>
  245. /// 接收服务器推送的2进制消息
  246. /// </summary>
  247. /// <param name="webSocket"></param>
  248. /// <param name="message"></param>
  249. private void OnBinaryMessageReceived(WebSocket webSocket, byte[] message)
  250. {
  251. Debug.Log("接收服务器推送的2进制消息的长度: " + message.Length);
  252. }
  253. /// <summary>
  254. /// 连接关闭时
  255. /// </summary>
  256. /// <param name="webSocket"></param>
  257. /// <param name="code"></param>
  258. /// <param name="message"></param>
  259. private void OnWebSocketClosed(WebSocket webSocket, UInt16 code, string message)
  260. {
  261. Debug.Log("WebSocket 关闭!");
  262. }
  263. /// <summary>
  264. /// 连接异常时,报错
  265. /// </summary>
  266. /// <param name="ws"></param>
  267. /// <param name="ex"></param>
  268. private void OnError(WebSocket ws, Exception ex)
  269. {
  270. string errorMsg = string.Empty;
  271. if (ws.InternalRequest.Response != null)
  272. {
  273. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}",
  274. ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  275. }
  276. Debug.Log("错误发生: " + (ex != null ? ex.Message : "不明错误: " + errorMsg));
  277. }
  278. /// <summary>
  279. /// 报错
  280. /// </summary>
  281. /// <param name="ws"></param>
  282. /// <param name="error"></param>
  283. private void OnErrorDesc(WebSocket ws, string error)
  284. {
  285. Debug.Log("错误: " + error);
  286. }
  287. /// <summary>
  288. /// 针对大文本或2进制消息
  289. /// </summary>
  290. /// <param name="webSocket"></param>
  291. /// <param name="frame"></param>
  292. private void OnIncompleteFrame(WebSocket webSocket, WebSocketFrameReader frame)
  293. {
  294. }
  295. #endregion
  296. #region Socket.IO
  297. /// <summary>
  298. /// Socket.IO测试使用
  299. /// 提供了基于事件的实时双向通讯.将WebSocket和Polling机制以及其它的实时通信方式封装成通用的接口
  300. /// </summary>
  301. private void SetSocketIO(string url)
  302. {
  303. socketManager = new SocketManager(new Uri(url));
  304. //默认socket套接字获取
  305. Socket root = socketManager.Socket;
  306. //Socket nsp = socketManager["/customNamespace"];
  307. //Socket nsp2 = socketManager.GetSocket("/customNamespace");
  308. //服务器事件订阅
  309. socketManager.Socket.On("login", OnLogin);
  310. socketManager.Socket.On("connect", OnConnect);
  311. socketManager.Socket.On("connecting",OnConnecting);
  312. socketManager.Socket.On("customEvent",OnCustomEvent);
  313. socketManager.Socket.On("disconnect",OnDisconnect);
  314. socketManager.Socket.On("reconnect",OnReConnect);
  315. socketManager.Socket.On("reconnecting",OnReConnecting);
  316. socketManager.Socket.On("reconnect_attempt",OnAttemptToReConnect);
  317. socketManager.Socket.On("reconnect_failed",OnReconnectFailed);
  318. socketManager.Socket.On("error",OnError);
  319. socketManager.Socket.On(SocketIOEventTypes.Error,OnError);
  320. socketManager.Socket.On("frame",OnFrame);
  321. //不自动解码设置
  322. socketManager.Socket.On("frame2", OnFrame2,false);
  323. }
  324. private void ResetSocketIO()
  325. {
  326. //服务器事件取消
  327. socketManager.Socket.Off("login", OnLogin);
  328. socketManager.Socket.Off("connect", OnConnect);
  329. socketManager.Socket.Off("connecting", OnConnecting);
  330. socketManager.Socket.Off("customEvent", OnCustomEvent);
  331. socketManager.Socket.Off("disconnect", OnDisconnect);
  332. socketManager.Socket.Off("reconnect", OnReConnect);
  333. socketManager.Socket.Off("reconnecting", OnReConnecting);
  334. socketManager.Socket.Off("reconnect_attempt", OnAttemptToReConnect);
  335. socketManager.Socket.Off("reconnect_failed", OnReconnectFailed);
  336. socketManager.Socket.Off("error", OnError);
  337. socketManager.Socket.Off(SocketIOEventTypes.Error, OnError);
  338. socketManager.Socket.Off("frame", OnFrame);
  339. socketManager.Socket.Off("frame2", OnFrame2);
  340. }
  341. /// <summary>
  342. /// 向服务器发送请求
  343. /// </summary>
  344. /// <param name="eventName"></param>
  345. /// <param name="arg"></param>
  346. public void SocketIOReq(string eventName, params object[] arg)
  347. {
  348. socketManager.Socket.Emit(eventName,arg);
  349. }
  350. /// <summary>
  351. /// 向服务器发送请求,带回调
  352. /// </summary>
  353. /// <param name="eventName"></param>
  354. /// <param name="onServerCallBack"></param>
  355. /// <param name="arg"></param>
  356. public void SocketIOReq2(string eventName, OnServerCallBack onServerCallBack, params object[] args)
  357. {
  358. socketManager.Socket.Emit(eventName,onServerCallBack,args);
  359. }
  360. private Texture2D texture;
  361. /// <summary>
  362. /// 数据解析
  363. /// </summary>
  364. /// <param name="socket"></param>
  365. /// <param name="packet"></param>
  366. /// <param name="args"></param>
  367. private void OnFrame(Socket socket, Packet packet, params object[] args)
  368. {
  369. texture = new Texture2D(100,50);
  370. texture.LoadImage(packet.Attachments[0]);
  371. }
  372. /// <summary>
  373. /// 数据解析2
  374. /// </summary>
  375. /// <param name="socket"></param>
  376. /// <param name="packet"></param>
  377. /// <param name="args"></param>
  378. private void OnFrame2(Socket socket, Packet packet, params object[] args)
  379. {
  380. texture = new Texture2D(100, 50);
  381. texture.LoadImage(packet.Attachments[0]);
  382. }
  383. /// <summary>
  384. /// 登陆事件监听
  385. /// </summary>
  386. /// <param name="socket"></param>
  387. /// <param name="packet"></param>
  388. /// <param name="args"></param>
  389. private void OnLogin(Socket socket, Packet packet, params object[] args)
  390. {
  391. }
  392. /// <summary>
  393. /// 连接
  394. /// </summary>
  395. /// <param name="socket"></param>
  396. /// <param name="packet"></param>
  397. /// <param name="args"></param>
  398. private void OnConnect(Socket socket, Packet packet, params object[] args)
  399. {
  400. }
  401. /// <summary>
  402. /// 连接中
  403. /// </summary>
  404. /// <param name="socket"></param>
  405. /// <param name="packet"></param>
  406. /// <param name="args"></param>
  407. private void OnConnecting(Socket socket, Packet packet, params object[] args)
  408. {
  409. }
  410. /// <summary>
  411. /// 任意的自定义事件
  412. /// </summary>
  413. /// <param name="socket"></param>
  414. /// <param name="packet"></param>
  415. /// <param name="args"></param>
  416. private void OnCustomEvent(Socket socket, Packet packet, params object[] args)
  417. {
  418. }
  419. /// <summary>
  420. /// 连接断开时:传输断开,socketmanager关闭,socket关闭,无心跳消息返回等
  421. /// </summary>
  422. /// <param name="socket"></param>
  423. /// <param name="packet"></param>
  424. /// <param name="args"></param>
  425. private void OnDisconnect(Socket socket, Packet packet, params object[] args)
  426. {
  427. }
  428. /// <summary>
  429. /// 重连上
  430. /// </summary>
  431. /// <param name="socket"></param>
  432. /// <param name="packet"></param>
  433. /// <param name="args"></param>
  434. private void OnReConnect(Socket socket, Packet packet, params object[] args)
  435. {
  436. }
  437. /// <summary>
  438. /// 重连中
  439. /// </summary>
  440. /// <param name="socket"></param>
  441. /// <param name="packet"></param>
  442. /// <param name="args"></param>
  443. private void OnReConnecting(Socket socket, Packet packet, params object[] args)
  444. {
  445. }
  446. /// <summary>
  447. /// 尝试重连
  448. /// </summary>
  449. /// <param name="socket"></param>
  450. /// <param name="packet"></param>
  451. /// <param name="args"></param>
  452. private void OnAttemptToReConnect(Socket socket, Packet packet, params object[] args)
  453. {
  454. }
  455. /// <summary>
  456. /// 重连失败
  457. /// </summary>
  458. /// <param name="socket"></param>
  459. /// <param name="packet"></param>
  460. /// <param name="args"></param>
  461. private void OnReconnectFailed(Socket socket, Packet packet, params object[] args)
  462. {
  463. }
  464. /// <summary>
  465. /// 错误信息
  466. /// </summary>
  467. /// <param name="socket"></param>
  468. /// <param name="packet"></param>
  469. /// <param name="args"></param>
  470. private void OnError(Socket socket, Packet packet, params object[] args)
  471. {
  472. Error error = args[0] as Error;
  473. switch (error.Code)
  474. {
  475. case SocketIOErrors.User:
  476. Debug.Log("Exception in an event handler!");
  477. break;
  478. case SocketIOErrors.Internal:
  479. Debug.Log("Internal error!");
  480. break;
  481. default:
  482. Debug.Log("Server error!");
  483. break;
  484. }
  485. Debug.Log(error.ToString());
  486. }
  487. #endregion
  488. #region SingalR
  489. /// <summary>
  490. /// SingalR实现实时通信
  491. /// </summary>
  492. public void SetSingalR(string url)
  493. {
  494. singalRConnect = new Connection(new Uri(url));
  495. singalRConnect.OnConnected += OnConnected;
  496. singalRConnect.OnClosed += OnClosed;
  497. singalRConnect.OnError += OnError;
  498. singalRConnect.OnReconnecting += OnReconnecting;
  499. singalRConnect.OnReconnected += OnReconnected;
  500. singalRConnect.OnStateChanged += OnStateChnaged;
  501. singalRConnect.OnNonHubMessage += OnNonHubMessage;
  502. singalRConnect.RequestPreparator += RequestPreparator;
  503. singalRConnect.Open();
  504. }
  505. /// <summary>
  506. /// 连接上了
  507. /// </summary>
  508. /// <param name="connection"></param>
  509. private void OnConnected(Connection connection)
  510. {
  511. Debug.Log("连接上了 SignalR server!");
  512. }
  513. /// <summary>
  514. /// 关闭的
  515. /// </summary>
  516. /// <param name="connection"></param>
  517. private void OnClosed(Connection connection)
  518. {
  519. Debug.Log("连接关闭");
  520. }
  521. /// <summary>
  522. /// 错误消息
  523. /// </summary>
  524. /// <param name="connection"></param>
  525. /// <param name="error"></param>
  526. private void OnError(Connection connection, string error)
  527. {
  528. }
  529. /// <summary>
  530. /// 重连中
  531. /// </summary>
  532. /// <param name="connection"></param>
  533. private void OnReconnecting(Connection connection)
  534. {
  535. Debug.Log("Reconnecting");
  536. }
  537. /// <summary>
  538. /// 重连上了
  539. /// </summary>
  540. /// <param name="connection"></param>
  541. private void OnReconnected(Connection connection)
  542. {
  543. Debug.Log("Reconnected");
  544. }
  545. /// <summary>
  546. /// 连接状态变化
  547. /// </summary>
  548. /// <param name="connection"></param>
  549. /// <param name="oldState"></param>
  550. /// <param name="newState"></param>
  551. private void OnStateChnaged(Connection connection, ConnectionStates oldState, ConnectionStates newState)
  552. {
  553. Debug.Log(string.Format("State Changed {0} -> {1}", oldState, newState));
  554. }
  555. /// <summary>
  556. /// NonHua消息监听
  557. /// </summary>
  558. /// <param name="connection"></param>
  559. /// <param name="data"></param>
  560. private void OnNonHubMessage(Connection connection, object data)
  561. {
  562. Debug.Log("Message from server: " + data.ToString());
  563. }
  564. /// <summary>
  565. /// 请求自定义
  566. /// </summary>
  567. /// <param name="connection"></param>
  568. /// <param name="req"></param>
  569. /// <param name="type"></param>
  570. private void RequestPreparator(Connection connection, HTTPRequest req, RequestTypes type)
  571. {
  572. req.Timeout = TimeSpan.FromSeconds(30);
  573. }
  574. /// <summary>
  575. /// 消息发送给服务器
  576. /// </summary>
  577. /// <param name="type"></param>
  578. /// <param name="value"></param>
  579. public void SendMsg(string type, string value)
  580. {
  581. singalRConnect.Send(new { Type = type, Value = value});
  582. }
  583. /// <summary>
  584. /// json格式发送:
  585. /// { Type: ‘Broadcast’, Value: ‘Hello SignalR World!’ }
  586. /// </summary>
  587. /// <param name="jsonStr"></param>
  588. public void SendMsg2(string jsonStr)
  589. {
  590. singalRConnect.SendJson(jsonStr);
  591. }
  592. #endregion
  593. void Awake()
  594. {
  595. //全局配置一些变量
  596. //和服务器的最大连接数设置
  597. HTTPManager.MaxConnectionPerServer = 4;
  598. //连接一次请求后是否还保持活跃
  599. HTTPManager.KeepAliveDefaultValue = false;
  600. //是否关闭缓存机制,默认开启
  601. HTTPManager.IsCachingDisabled = true;
  602. //连接完成了最后一次请求后,多长时间销毁
  603. HTTPManager.MaxConnectionIdleTime = TimeSpan.FromSeconds(20);
  604. //cookie机制是否开启
  605. HTTPManager.IsCookiesEnabled = true;
  606. HTTPManager.CookieJarSize = 10485760;
  607. //是否禁止cookie写到磁盘中
  608. HTTPManager.EnablePrivateBrowsing = false;
  609. //时间限制
  610. HTTPManager.ConnectTimeout = TimeSpan.FromSeconds(20);
  611. HTTPManager.RequestTimeout = TimeSpan.FromSeconds(60);
  612. //代理服务器
  613. HTTPManager.Proxy = new HTTPProxy(new Uri("http://localhost:3128"));
  614. //服务器证书校验
  615. HTTPManager.DefaultCertificateVerifyer = new CustomVerifier();
  616. HTTPManager.UseAlternateSSLDefaultValue = true;
  617. }
  618. // Use this for initialization
  619. void Start () {
  620. request1 = GetRequest("http://server.com/path");
  621. //根据连接请求使用情况,设置是否保持请求连接的活跃【默认:true】
  622. request1.IsKeepAlive = false;
  623. //关于是否缓存【默认:false】
  624. request1.DisableCache = false;
  625. //凭证【可选】
  626. request1.Credentials = new Credentials("userName","passwoed");
  627. //携带之前服务器认证成功生成的cookie如身份认证参数过去,方便访问。【可选】
  628. request1.Cookies.Add(new Cookie("Name","Value"));
  629. //代理服务器设置【可选】
  630. request1.Proxy = new HTTPProxy(new Uri("http://localhost:3128"));
  631. //下载进度回调设置【可选】
  632. request1.OnProgress = OnDownloadProgress;
  633. //与服务器建立连接的时间限制设定【可选】
  634. request1.ConnectTimeout = TimeSpan.FromSeconds(2);
  635. //与服务器请求到响应的总时间限制的设定【可选】
  636. request1.Timeout = TimeSpan.FromSeconds(10);
  637. //请求处理的优先级设置【可选】
  638. request1.Priority = -1;
  639. //服务器证书验证【可选】
  640. request1.CustomCertificateVerifyer = new CustomVerifier();
  641. request1.UseAlternateSSL = true;
  642. //重定向【可选】
  643. request1.OnBeforeRedirection += OnBeforeRedirect;
  644. 手动终止请求
  645. //request1.Abort();
  646. //一些统计数据
  647. GeneralStatistics statis = HTTPManager.GetGeneralStatistics(StatisticsQueryFlags.All);
  648. Debug.Log("[Connection] RequestsInQueue:" + statis.RequestsInQueue+ " Connections:"+statis.Connections
  649. + " ActiveConnections:"+statis.ActiveConnections+ " FreeConnections:"+statis.FreeConnections
  650. + " RecycledConnections:"+statis.RecycledConnections);
  651. Debug.Log("[Cache] CacheEntityCount:"+statis.CacheEntityCount+ " CacheSize:"+statis.CacheSize);
  652. Debug.Log("[Cookie] CookieCount:"+statis.CookieCount+ " CookieJarSize:"+statis.CookieJarSize);
  653. }
  654. /// <summary>
  655. /// 重定向处理:服务器无法处理客户端发送过来的请求(request),服务器告诉客户端跳转到可以处理请求的url上
  656. /// </summary>
  657. /// <param name="originalRequest"></param>
  658. /// <param name="response"></param>
  659. /// <param name="redirectUri"></param>
  660. /// <returns></returns>
  661. private bool OnBeforeRedirect(HTTPRequest originalRequest, HTTPResponse response, Uri redirectUri)
  662. {
  663. //状态码302时,做重定向处理
  664. if (response.StatusCode == 302)
  665. {
  666. }
  667. return true;
  668. }
  669. /// <summary>
  670. /// 下载进度回调
  671. /// </summary>
  672. /// <param name="request"></param>
  673. /// <param name="downloaded"></param>
  674. /// <param name="length"></param>
  675. private void OnDownloadProgress(HTTPRequest originalRequest, long downloaded, long downloadLength)
  676. {
  677. float progressPercent = (downloaded / (float)downloadLength) * 100.0f;
  678. Debug.Log("请求的下载速度: " + progressPercent.ToString("F2") + "%");
  679. }
  680. // Update is called once per frame
  681. void Update () {
  682. }
  683. }

插件下载地址:BestHttp.unityPackage 提取码:l5g9

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/126456
推荐阅读
相关标签
  

闽ICP备14008679号