public LocationRestResponse sendRequestToIPStack(HttpClient clientt, string URL) { LocationRestResponse restResponse = new LocationRestResponse(); using (HttpClient client = new HttpClient()) { //if it's the first time submitting a request if (client.BaseAddress == null) { client.BaseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); } HttpResponseMessage response; //send request and get the response try { response = client.GetAsync(_LOCATION_API_KEY).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. } //if there is no internet connection the exception below e occurs catch (AggregateException) { restResponse.Message = "No internet connection"; return(restResponse); } if (response.IsSuccessStatusCode) { // Parse the response body. LocationData parsedData = null; try { parsedData = response.Content.ReadAsAsync <LocationData>().Result; //parsing json into RootObject } catch (Exception) { restResponse.Message = "Something went wrong. Please try again"; return(restResponse); } restResponse.Message = "Success"; restResponse.Root = parsedData; } else { restResponse.Message = $"Can't find place with name {CityName}"; } } return(restResponse); }
//Retreiving location data private LocationData sendRequestLocation() { LocationRestResponse response = rest_request.sendRequestToIPStack(client, rest_request.LOCATION_URL); //get response from server if (response.Root == null) { NotifyUser(response.Message); //something wen't wrong in the response return(null); } //if the json parsed, but some of the importan't data is null if (response.Root.city == null) { NotifyUser("Something went wrong. Please try again in a couple of minutes"); return(null); } return(response.Root); }