从URL获取JSON,保存到文件,最后创建CreateActivationService

时间:2018-10-09 02:18:13

标签: c# uwp windows-template-studio

使用Visual Studio的Template Studio扩展,我生成了一个项目解决方案库,现在尝试在继续呈现页面视图之前,通过HTTP请求插入应用程序加载过程。

App.xaml.cs

using System;

using Braytech_3.Services;

using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.UI.Xaml;

namespace Braytech_3
{
    public sealed partial class App : Application
    {
        private Lazy<ActivationService> _activationService;

        private ActivationService ActivationService
        {
            get { return _activationService.Value; }
        }

        public App()
        {
            InitializeComponent();

            APIRequest();

            // Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class.
            _activationService = new Lazy<ActivationService>(CreateActivationService);
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!args.PrelaunchActivated)
            {
                await ActivationService.ActivateAsync(args);
            }
        }

        protected override async void OnActivated(IActivatedEventArgs args)
        {
            await ActivationService.ActivateAsync(args);
        }

        private async void APIRequest()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                APITempSave(httpResponseBody);

            }
            catch (Exception ex)
            {

            }
        }

        private async void APITempSave(string json)
        {
            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

            if (await tempFolder.TryGetItemAsync("APIData.json") != null)
            {
                StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }
            else
            {
                StorageFile APIData = await tempFolder.CreateFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }

        }

        private ActivationService CreateActivationService()
        {
            return new ActivationService(this, typeof(Views.VendorsPage), new Lazy<UIElement>(CreateShell));
        }

        private UIElement CreateShell()
        {
            return new Views.ShellPage();
        }
    }
}

我认为我需要做的是一旦致电_activationService = new Lazy<ActivationService>(CreateActivationService);后再致电APITempSave(),但是我不确定如何以及最佳做法是什么。

任何指导将不胜感激!

1 个答案:

答案 0 :(得分:1)

在进一步研究并熟悉了所生成的解决方案以及对Googling的await,async和Tasks <>的更多了解之后,我能够将请求与服务一起实现,例如ThemeSelector和ToastNotifications。

ThemeSelector是为当前用户确定明暗主题模式时首先要调用的东西之一,因此我能够围绕它建模服务并同时调用它。

这显然是模板工作室生成的代码所特有的,但是一些概念是共享的,将来如果其他任何人寻找相似的答案,也许他们会找到的。

APIRequest.cs(服务)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace Braytech_3.Services
{
    public static class APIRequest
    {

        internal static async Task Request()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                await APITempSave(httpResponseBody);

            }
            catch (Exception ex)
            {

            }
        }

        internal static async Task APITempSave(string json)
        {
            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

            if (await tempFolder.TryGetItemAsync("APIData.json") != null)
            {
                StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }
            else
            {
                StorageFile APIData = await tempFolder.CreateFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }

        }
    }
}

ActivationService.cs(最初由App.xaml.cs调用)

private async Task InitializeAsync()
{
    await ThemeSelectorService.InitializeAsync();
    await APIRequest.Request();
}