1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using UnityEngine;
- using UnityEngine.Networking;
- using System;
- using System.Collections;
- using Google.Protobuf;
- //using Protobuf;
- using System.IO;
- using GFGGame.Launcher;
- namespace GFGGame
- {
- class HttpProtobufTool : SingletonMonoBase<HttpProtobufTool>
- {
-
- //jsonString 为json字符串,post提交的数据包为json
- public void Post(string prefixUrl, string methodName, byte[] bodyRaw, Action<string> callback)
- {
- StartCoroutine(PostRequest(prefixUrl, methodName, bodyRaw, callback));
- }
- public IEnumerator PostRequest(string prefixUrl, string methodName, byte[] bodyRaw, Action<string> callback)
- {
- string url = prefixUrl + methodName;
- Debug.Log(string.Format("post url:{0}", url));
- using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
- {
- webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
- webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
- webRequest.timeout = LauncherConfig.HTTP_POST_TIME_OUT;
- //http header 的内容
- webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
- // webRequest.timeout;
- yield return webRequest.SendWebRequest();
- ResultHandler(webRequest, callback, "", () =>
- {
- Post(prefixUrl, methodName, bodyRaw, callback);
- });
- }
- }
- public void ResultHandler(UnityWebRequest webRequest, Action<string> callback, string tag, Action retryCall)
- {
- string paramCallback = null;
- if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
- {
- Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
- Alert.Show("连接服务器失败:\n请检查网络和服务器状态")
- .SetRightButton(true, "重试", (object data) =>
- {
- retryCall();
- });
- }
- else
- {
- byte[] data = webRequest.downloadHandler.data;
- //StoreRequest storeRequest = StoreRequest.Parser.ParseFrom(data);
- //Debug.Log("from server " + storeRequest.ToString() + "\ntag = " + tag);
- paramCallback = webRequest.downloadHandler.text;
- callback?.Invoke(paramCallback);
- }
- }
-
- }
- }
|