コード例 #1
0
        private static async Task <Response> DevicePortalAuthorizationAsync(DeviceInfo targetDevice)
        {
            UnityWebRequest webRequest = UnityWebRequest.Get(FinalizeUrl(targetDevice.IP));

            webRequest.timeout            = 5;
            webRequest.certificateHandler = DevicePortalCertificateHandler;
            webRequest.disposeCertificateHandlerOnDispose = false;
            webRequest.SetRequestHeader("Authorization", targetDevice.Authorization["Authorization"]);

            await webRequest.SendWebRequest();

            long responseCode = webRequest.responseCode;

#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 (responseCode == 401)
                {
                    return(new Response(false, "Invalid Credentials", null, responseCode));
                }

                if (webRequest.GetResponseHeaders() == null)
                {
                    return(new Response(false, "Device Not Found | No Response Headers", null, responseCode));
                }

                string responseHeaders = webRequest.GetResponseHeaders().Aggregate(string.Empty, (current, header) => $"\n{header.Key}: {header.Value}");

                byte[] downloadHandlerData = webRequest.downloadHandler?.data;
                string downloadHandlerText = await ResponseUtils.BytesToString(downloadHandlerData);

                Debug.LogError($"REST Auth Error: {responseCode}\n{downloadHandlerText}{responseHeaders}");
                return(new Response(false, $"{downloadHandlerText}", downloadHandlerData, responseCode));
            }

            return(new Response(true, new Task <string>(() => webRequest.GetResponseHeader("Set-Cookie")), () => webRequest.downloadHandler?.data, responseCode));
        }