コード例 #1
0
        public static async Task <UnityWebRequest> PostAsync(string url, string details, RequestAuthMiddleware authMiddleware = null)
        {
            string jsonData = JsonConvert.SerializeObject(new{ query = details });

            byte[]          postData = Encoding.ASCII.GetBytes(jsonData);
            UnityWebRequest request  = UnityWebRequest.Post(url, UnityWebRequest.kHttpVerbPOST);

            request.uploadHandler = new UploadHandlerRaw(postData);
            request.SetRequestHeader("Content-Type", "application/json");
            if (authMiddleware != null)
            {
                authMiddleware.Prepare(request);
                Debug.LogFormat("Auth Header: {0}", request.GetRequestHeader("Authorization"));
            }
            OnRequestBegin requestBegin = new OnRequestBegin();

            requestBegin.FireEvent();

            try{
                await request.SendWebRequest();
            }
            catch (Exception e) {
                Debug.Log("Testing exceptions");
                OnRequestEnded requestFailed = new OnRequestEnded(e);
                requestFailed.FireEvent();
            }
            Debug.Log(request.downloadHandler.text);

            OnRequestEnded requestSucceeded = new OnRequestEnded(request.downloadHandler.text);

            requestSucceeded.FireEvent();
            return(request);
        }
コード例 #2
0
ファイル: WebHandler.cs プロジェクト: Vlad119/aircond3D
    private async void PostJson(string url, string dataString, UnityAction <string> DoIfSuccess = null, bool addTokenHeader = false)
    {
        var endUrl = servAddress + url;
        var req    = await IRequestSend(() =>
        {
            var request             = new UnityWebRequest(endUrl, "POST");
            byte[] bodyRaw          = Encoding.UTF8.GetBytes(dataString);
            var uploadHandler       = new UploadHandlerRaw(bodyRaw);
            request.uploadHandler   = uploadHandler;
            request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            if (!addTokenHeader)
            {
                request.SetRequestHeader("content-type", "application/json");
            }
            else
            {
                request.SetRequestHeader("content-type", "application/json");
                request.SetRequestHeader("Token", AppManager.Instance.userInfo.access_token);
            }
            print(request.GetRequestHeader("content-type") + "   " + (addTokenHeader ? request.GetRequestHeader("token") : "") + "    " + request.url + "    " + Encoding.UTF8.GetString(request.uploadHandler.data));
            return(request);
        });

        Debug.Log("All OK");
        Debug.Log("Status Code: " + req.responseCode);
        DoIfSuccess?.Invoke(req.downloadHandler.text);
    }
コード例 #3
0
        private IEnumerator SendRequest(HttpRequestType requestType, string requestURL, OnSuccess successResponse, OnErrorResponse errorResponse, HTTPParam data = default, int timeOut = 10, string headerAPIValue = "")
        {
            string   debug     = string.Empty;
            DateTime debugTime = DateTime.UtcNow;

            LogBeforeSend(ref debug, ref requestType, ref requestURL, ref data);

            UnityWebRequest engine = CreateWebReqeust(requestType, ref requestURL, ref data, timeOut);

            InitAndSetHeaderAPI(ref engine, headerAPIValue);//标记HTTP请求头部数据,区分发送同一个请求的不同业务

            mIsNetWorking = true;
            yield return(engine.SendWebRequest());

            mIsNetWorking = false;

            LogTimeUsed(ref debug, ref engine, debugTime);

            string headerAPI = engine.GetRequestHeader("api");

            CheckRequestError(ref engine, ref debug, out int errorStatu);

            Responsed(errorStatu, ref engine, successResponse, errorResponse, ref data, ref requestURL, ref debug);

            engine.Dispose();
            RemoveHeaderAPI(ref headerAPI);
        }
コード例 #4
0
        private static async Task <Response> ProcessRequestAsync(UnityWebRequest webRequest, int timeout, Dictionary <string, string> headers = null, bool readResponseData = false)
        {
            if (timeout > 0)
            {
                webRequest.timeout = timeout;
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    webRequest.SetRequestHeader(header.Key, header.Value);
                }
            }

            // HACK: Workaround for extra quotes around boundary.
            if (webRequest.method == UnityWebRequest.kHttpVerbPOST ||
                webRequest.method == UnityWebRequest.kHttpVerbPUT)
            {
                string contentType = webRequest.GetRequestHeader("Content-Type");
                if (contentType != null)
                {
                    contentType = contentType.Replace("\"", "");
                    webRequest.SetRequestHeader("Content-Type", contentType);
                }
            }

            await webRequest.SendWebRequest();

#if UNITY_2020_1_OR_NEWER
            if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
#else
            if (webRequest.isNetworkError || webRequest.isHttpError)
#endif // UNITY_2020_1_OR_NEWER
            {
                if (webRequest.responseCode == 401)
                {
                    return(new Response(false, "Invalid Credentials", null, webRequest.responseCode));
                }

                if (webRequest.GetResponseHeaders() == null)
                {
                    return(new Response(false, "Device Unavailable", null, webRequest.responseCode));
                }

                string responseHeaders     = webRequest.GetResponseHeaders().Aggregate(string.Empty, (current, header) => $"\n{header.Key}: {header.Value}");
                string downloadHandlerText = webRequest.downloadHandler?.text;
                Debug.LogError($"REST Error: {webRequest.responseCode}\n{downloadHandlerText}{responseHeaders}");
                return(new Response(false, $"{responseHeaders}\n{downloadHandlerText}", webRequest.downloadHandler?.data, webRequest.responseCode));
            }
            if (readResponseData)
            {
                return(new Response(true, webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode));
            }
            else // This option can be used only if action will be triggered in the same scope as the webrequest
            {
                return(new Response(true, () => webRequest.downloadHandler?.text, () => webRequest.downloadHandler?.data, webRequest.responseCode));
            }
        }
コード例 #5
0
    static ApiWrapper()
    {
        var req    = new UnityWebRequest(HTTP_PROTOCOL + URL);
        var cookie = req.GetRequestHeader("Cookie");

        Cookie = new BehaviorSubject <string>(string.IsNullOrEmpty(cookie) ? "" : cookie);
        Cookie.Subscribe(Debug.Log);
    }
コード例 #6
0
        private void debugRequest(UnityWebRequest requester)
        {
            UploadHandler uploader = requester.uploadHandler;

            Debug.Log("Upload Data length: " + uploader.data.Length);
            Debug.Log("Upload Data Type: " + uploader.data.ToString());
            Debug.Log("Upload Handler Content Type: " + uploader.contentType);

            Debug.Log("Request Header Content-Type: " + requester.GetRequestHeader("Content-Type"));
            Debug.Log("URL: " + requester.url);
        }
コード例 #7
0
        private void AfterRequest(ref HTTPJsonRequestInfo info, ref string requestURL, ref JsonData data, ref UnityWebRequest engine, DateTime debugTime, ref string debug)
        {
            LogTimeUsed(ref debug, ref engine, debugTime);
            string headerAPI = engine.GetRequestHeader("api");

            CheckRequestError(ref engine, ref debug, out int errorStatu);

            Responsed(errorStatu, ref engine, info.successResponse, info.callback, info.errorResponse, ref data, ref requestURL, ref debug);

            engine.Dispose();
            RemoveHeaderAPI(ref headerAPI);
        }
コード例 #8
0
        public IEnumerator GetSpeechToText(byte[] fileName)           //"fileName" here refers to either a string containing the file path to be used with UploadHandlerFile, or a byte arr containing a Wav file.
        //parameters:
        {
            string language    = "en-GB";
            string format      = "simple";
            string accessToken = GetAccessToken();
            DownloadHandlerBuffer downloader = new DownloadHandlerBuffer();
            WWWForm form        = new WWWForm();
            string  queryString = string.Format("?language={0}&format={1}", language, format);
            string  endpoint    = sttHost + queryString;

            form.AddBinaryData("data", fileName);
            UnityWebRequest request = new UnityWebRequest();

            // Set the HTTP method
            // Construct the URI
            request.downloadHandler = downloader;
            request.url             = endpoint;
            request.method          = UnityWebRequest.kHttpVerbPOST;
            request.SetRequestHeader("Content-Type", @"audio/wav; codecs=audio/pcm; samplerate=16000");
            request.SetRequestHeader("Authorization", "Bearer " + accessToken);
            request.SetRequestHeader("Accept", "application/json;text/xml");
            request.uploadHandler             = (UploadHandler)(new UploadHandlerRaw(fileName));
            request.uploadHandler.contentType = @"audio/wav; codecs=audio/pcm; samplerate=16000";
            debugRequest(request);

            Debug.Log("Endpoint: " + request.url);
            Debug.Log("File to send: " + fileName);
            //request.uploadHandler = new UploadHandlerRaw(fileName); //FIX HERE
            //uploader.data = new StringContent(body, Encoding.UTF8, "application/ssml+xml");

            // Create a request
            debugRequest(request);
            Debug.Log(request.GetRequestHeader("Authorization"));
            Debug.Log("Calling the STT service. Please wait... \n");
            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log(request.error);
                Debug.Log(request.responseCode);
                Debug.Log(request.downloadHandler.data);
                Debug.Log(request.downloadHandler.text);
            }
            else
            {
                //Debug.Log (request.ToString ());
                if (request.isDone)
                {
                    Debug.Log("File Length: " + request.downloadedBytes);
                }
            }
        }
コード例 #9
0
        public Task <T> Execute()
        {
            var task = new TaskCompletionSource <UnityWebRequest>();

            return(MainThreadTask.Run(async() =>
            {
                Debug.Log($"Creating Web Request: {method} {endpoint}");
                var unityWebRequest = new UnityWebRequest(endpoint, method);
                unityWebRequest.SetRequestHeader("Accept", "application/json");
                if (needsAuth)
                {
                    var token = await authorizationProvider();
                    if (string.IsNullOrEmpty(token))
                    {
                        throw new RegenAuthenticationException("token was not retrieved for endpoint " + endpoint);
                    }

                    unityWebRequest.SetRequestHeader("Authorization", $"Bearer {token}");
                }

                if (body != null)
                {
                    unityWebRequest.SetRequestHeader("Content-Type", "application/json; charset=utf-8");
                    unityWebRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
                }

                unityWebRequest.downloadHandler = new DownloadHandlerBuffer();
                Debug.Log($"Sending Web Request: {method} {endpoint}");
                Debug.Log("Authorization: " + unityWebRequest.GetRequestHeader("Authorization"));
                var request = unityWebRequest.SendWebRequest();
                request.completed += operation =>
                {
                    var r = request.webRequest;
                    Debug.Log($"Web Request Complete: {method} {endpoint} {r.responseCode} {r.downloadHandler.text}");
                    if (r.isNetworkError)
                    {
                        task.SetException(new HttpRequestException("Encountered Network Error" + r.error));
                    }
                    else if (r.isHttpError)
                    {
                        task.SetException(new HttpResponseException("Encountered Http Error", r));
                    }
                    else
                    {
                        task.SetResult(r);
                    }
                };
                await task.Task;
                var map = mapping(task.Task.Result);
                Debug.Log($"Mapping Result: {map}");
                return map;
            }));
        }
コード例 #10
0
        public static string Info(this UnityWebRequest request)
        {
            var builder = new StringBuilder();

            builder.Append("Request URL: ");
            builder.Append(request.url);
            builder.Append("\nRequest Method: ");
            builder.Append(request.method);
            builder.Append("\nStatus Code: ");
            builder.Append(request.responseCode);
            if (request.GetRequestHeader("Cookie") != null)
            {
                builder.Append("\nCookies\n---------------\n");
                builder.Append(request.GetRequestHeader("Cookie").Replace(' ', '\n'));
                builder.Append("---------------");
            }
            if (request.GetResponseHeaders() != null)
            {
                builder.Append("\nResponse Headers\n---------------");
                foreach (var pair in request.GetResponseHeaders())
                {
                    builder.Append("\n");
                    builder.Append(pair.Key);
                    builder.Append(": ");
                    builder.Append(pair.Value);
                }
                builder.Append("\n---------------");
            }
            if (request.GetResponseBody() != null)
            {
                builder.Append("\nResponse body:");
                builder.Append(request.GetResponseBody());
            }
            builder.Append("\n---------------");
            return(builder.ToString());
        }
コード例 #11
0
        /// <summary>Creates and sends an image download request for the given url.</summary>
        protected UnityWebRequestAsyncOperation DownloadImage(string url)
        {
            Debug.Assert(!string.IsNullOrEmpty(url));

            // create new download
            UnityWebRequest webRequest = UnityWebRequest.Get(url);

            webRequest.downloadHandler = new DownloadHandlerTexture(true);

            // start download and attach callbacks
            var operation = webRequest.SendWebRequest();

            operation.completed += (o) =>
            {
                OnDownloadCompleted(operation.webRequest, url);
            };

            #if DEBUG
            if (PluginSettings.data.logAllRequests && logDownloads)
            {
                string        requestHeaders = "";
                List <string> requestKeys    = new List <string>(APIClient.UNITY_REQUEST_HEADER_KEYS);
                requestKeys.AddRange(APIClient.MODIO_REQUEST_HEADER_KEYS);

                foreach (string headerKey in requestKeys)
                {
                    string headerValue = webRequest.GetRequestHeader(headerKey);
                    if (headerValue != null)
                    {
                        requestHeaders += "\n" + headerKey + ": " + headerValue;
                    }
                }

                int timeStamp = ServerTimeStamp.Now;
                Debug.Log("IMAGE DOWNLOAD STARTED"
                          + "\nURL: " + webRequest.url
                          + "\nTimeStamp: [" + timeStamp.ToString() + "] "
                          + ServerTimeStamp.ToLocalDateTime(timeStamp).ToString()
                          + "\nHeaders: " + requestHeaders);
            }
            #endif

            return(operation);
        }
コード例 #12
0
        public static ImageRequest DownloadImage(string imageURL)
        {
            ImageRequest request = new ImageRequest();

            request.isDone = false;

            UnityWebRequest webRequest = UnityWebRequest.Get(imageURL);

            webRequest.downloadHandler = new DownloadHandlerTexture(true);

            #if DEBUG
            if (DownloadClient.logAllRequests)
            {
                string        requestHeaders = "";
                List <string> requestKeys    = new List <string>(APIClient.UNITY_REQUEST_HEADER_KEYS);
                requestKeys.AddRange(APIClient.MODIO_REQUEST_HEADER_KEYS);

                foreach (string headerKey in requestKeys)
                {
                    string headerValue = webRequest.GetRequestHeader(headerKey);
                    if (headerValue != null)
                    {
                        requestHeaders += "\n" + headerKey + ": " + headerValue;
                    }
                }

                Debug.Log("GENERATING DOWNLOAD REQUEST"
                          + "\nURL: " + webRequest.url
                          + "\nHeaders: " + requestHeaders
                          + "\n"
                          );
            }
            #endif

            var operation = webRequest.SendWebRequest();
            operation.completed += (o) => DownloadClient.OnImageDownloadCompleted(operation, request);

            return(request);
        }
コード例 #13
0
ファイル: WebScript.cs プロジェクト: ja1den/tanks
    public IEnumerator WriteScore(string name, int score)
    {
        string json = "{\"fields\": {\"score\": {\"integerValue\": \"" + score + "\"}, \"name\": {\"stringValue\": \"" + name + "\"} } }";

        using (UnityWebRequest request = UnityWebRequest.Put($"{URL}/scores", json))
        {
            // Create WebRequest
            request.method = UnityWebRequest.kHttpVerbPOST;
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Accept", "application/json");

            Debug.Log(request.GetRequestHeader("Content-Type") + " " + request.method);

            yield return(request.SendWebRequest());

            // Check for Error
            if (request.error != null)
            {
                Debug.Log("Error: (WriteScore)" + request.error);
            }
        }

        StartCoroutine(GetScores());
    }