HttpProtobufTool.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using System;
  4. using System.Collections;
  5. using Google.Protobuf;
  6. //using Protobuf;
  7. using System.IO;
  8. using GFGGame.Launcher;
  9. namespace GFGGame
  10. {
  11. class HttpProtobufTool : SingletonMonoBase<HttpProtobufTool>
  12. {
  13. //jsonString 为json字符串,post提交的数据包为json
  14. public void Post(string prefixUrl, string methodName, byte[] bodyRaw, Action<string> callback)
  15. {
  16. StartCoroutine(PostRequest(prefixUrl, methodName, bodyRaw, callback));
  17. }
  18. public IEnumerator PostRequest(string prefixUrl, string methodName, byte[] bodyRaw, Action<string> callback)
  19. {
  20. string url = prefixUrl + methodName;
  21. Debug.Log(string.Format("post url:{0}", url));
  22. using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  23. {
  24. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  25. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  26. webRequest.timeout = LauncherConfig.HTTP_POST_TIME_OUT;
  27. //http header 的内容
  28. webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
  29. // webRequest.timeout;
  30. yield return webRequest.SendWebRequest();
  31. ResultHandler(webRequest, callback, "", () =>
  32. {
  33. Post(prefixUrl, methodName, bodyRaw, callback);
  34. });
  35. }
  36. }
  37. public void ResultHandler(UnityWebRequest webRequest, Action<string> callback, string tag, Action retryCall)
  38. {
  39. string paramCallback = null;
  40. if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
  41. {
  42. Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
  43. Alert.Show("连接服务器失败:\n请检查网络和服务器状态")
  44. .SetRightButton(true, "重试", (object data) =>
  45. {
  46. retryCall();
  47. });
  48. }
  49. else
  50. {
  51. byte[] data = webRequest.downloadHandler.data;
  52. //StoreRequest storeRequest = StoreRequest.Parser.ParseFrom(data);
  53. //Debug.Log("from server " + storeRequest.ToString() + "\ntag = " + tag);
  54. paramCallback = webRequest.downloadHandler.text;
  55. callback?.Invoke(paramCallback);
  56. }
  57. }
  58. }
  59. }