Exemplo n.º 1
0
        static async Task <TextResponse> RequestHttpAsync(HttpMethod method, string endPointPath,
                                                          PropertyCollection parameters, PropertyCollection headers,
                                                          RequestType requestType, ResponseType responseType, bool attemptTokenRefresh)
        {
            if (!MASApplication.IsRegistered)
            {
                ErrorFactory.ThrowError(ErrorCode.ApplicationNotRegistered);
            }

            if (!MASDevice.Current.IsRegistered)
            {
                ErrorFactory.ThrowError(ErrorCode.DeviceNotRegistered);
            }

            string url  = endPointPath;
            string body = null;

            if (method == HttpMethod.GET || method == HttpMethod.DELETE)
            {
                var builder = new HttpUrlBuilder(endPointPath);
                if (parameters != null)
                {
                    foreach (var paramInfo in parameters.Properties)
                    {
                        builder.Add(paramInfo.Key, paramInfo.Value);
                    }
                }

                url = builder.ToString();
            }
            else if (parameters != null)
            {
                body = FormatBody(requestType, parameters.Properties);
            }


            MASUser requestUser = null;

            if (MASUser.Current != null && MASUser.Current.IsLoggedIn)
            {
                requestUser = MASUser.Current;
            }
            else if (MASApplication.Current.Client != null)
            {
                requestUser = MASApplication.Current.Client;
            }

            var requestHeaders = await SetupRequestHeaders(requestUser, headers?.Properties, requestType, responseType);

            try
            {
                var requestResponse = await HttpRequestFactory.RequestTextAsync(new HttpRequestInfo()
                {
                    Url         = url,
                    Method      = method,
                    Headers     = requestHeaders,
                    Body        = body,
                    Certificate = MASDevice.Current.Certificate
                });

                return(ToMASResponse(requestResponse));
            }
            catch (MASException exp)
            {
                if (requestUser == null || attemptTokenRefresh == false || exp.MASErrorCode != ErrorCode.TokenAccessExpired)
                {
                    throw exp;
                }
            }

            // Our token has expired, attempt to refresh it and try again!
            await requestUser.RefreshAccessTokenAsync();

            // Lets not try to refresh token after our first attempt
            return(await RequestHttpAsync(method, endPointPath, parameters,
                                          headers, requestType, responseType, false));
        }