Esempio n. 1
0
        public async Task <List <PlanetModel> > GetAllPlanetsAsync()
        {
            StringBuilder url = new StringBuilder();

            //base address https://swapi.co/api/
            url.Append(ApiHelper.ApiClient.BaseAddress.ToString());
            url.Append("planets");

            using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url.ToString()))
            {
                if (response.IsSuccessStatusCode)
                {
                    List <PlanetModel> planets = new List <PlanetModel>();

                    //get first page of planets
                    string responseString = await response.Content.ReadAsStringAsync();

                    JObject results = JsonConvert.DeserializeObject <JObject>(responseString);
                    planets.AddRange(
                        results.Value <JArray>("results")
                        .ToObject <List <PlanetModel> >());
                    string next = results.GetValue("next").Value <string>();

                    //fetch the rest of the planet pages
                    while (!string.IsNullOrWhiteSpace(next) && next != "null")
                    {
                        PlanetResponseModel planetResponse = await GetPlanetPageAsync(next);

                        next = planetResponse.ResponseNext;
                        planets.AddRange(planetResponse.planets);
                    }

                    return(planets);
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
Esempio n. 2
0
        public async Task <PlanetResponseModel> GetPlanetPageAsync(string url)
        {
            using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url.ToString()))
            {
                if (response.IsSuccessStatusCode)
                {
                    PlanetResponseModel planetResponse = new PlanetResponseModel();

                    string responseString = await response.Content.ReadAsStringAsync();

                    JObject results = JsonConvert.DeserializeObject <JObject>(responseString);
                    planetResponse.planets.AddRange(
                        results.Value <JArray>("results")
                        .ToObject <List <PlanetModel> >());
                    planetResponse.ResponseNext = results.GetValue("next").Value <string>();

                    return(planetResponse);
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }