API connection error

Eduardo Gomez Romero 1,355 Reputation points
2024-09-09T00:01:31.2933333+00:00

I cannot believe an API call is giving me errors lol

I really don't know what happening.

I tested to if my Api call was ok, and it is ok

User's image

I get 200 status code OK

When I put it in Maui strange things happen

WindowsUser's image

Android

User's image

for Android I made sure to modify the manifest

	<application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true" android:usesCleartextTraffic="true">
		<meta-data android:name="com.google.android.geo.API_KEY" android:value="xxxxx" />
		<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
		
	</application>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

My httpServce

    public class HttpService(HttpClient httpClient, IConnectivity connectivity) {
        public async Task<T?> GetAsync<T>(string url) {
            if (connectivity.NetworkAccess != NetworkAccess.Internet) {
                await Shell.Current.DisplayAlert("Error",
                    "No internet connectivity"
                    , "OK");
                return default;
            }
            try {
                var response =
                    await httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode) {
                    var jsonData = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Received JSON: " + jsonData); // Debugging line
                    var data = await response.Content.ReadFromJsonAsync<T>();
                    return data;
                } else {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    await Shell.Current.DisplayAlert("HTTP Error", $"Status code: {response.StatusCode}", "OK");
                }
            } catch (HttpRequestException httpEx) {
                await Shell.Current.DisplayAlert("HTTP Error", httpEx.Message, "OK");
                Console.WriteLine("Request URL: " + url); // Debugging line
            } catch (JsonException jsonEx) {
                await Shell.Current.DisplayAlert("JSON Error", jsonEx.Message, "OK");
            } catch (Exception ex) {
                await Shell.Current.DisplayAlert("Unknown error", ex.Message, "OK");
            }
            return default;
        }
    }
}


viewModel


        private readonly HttpService httpService;

        private ObservableCollection<EnergyNews> NewsList {  get; set; }

        public HomePageViewModel(HttpService httpService) {

            this.httpService = httpService;
            LoadNews();
        }

        private async void LoadNews() {

            var h = await httpService.GetAsync<object>("https://newsapi.org/v2/everything?q=renewable+energy&apiKey=5963dd2ef5ff48b9bfa99e902bd55716");
        }

    }
}

Note: I am living my Api key here, so you can test and see that everything is ok, because this is the first time this happens to me

Class

    public class Source {

        [JsonPropertyName("id")]
        public string? Id { get; set; }

        [JsonPropertyName("name")]
        public string? Name { get; set; }
    }

    public class Article {

        [JsonPropertyName("source")]
        public Source? Source { get; set; }

        [JsonPropertyName("author")]
        public string? Author { get; set; }

        [JsonPropertyName("title")]
        public string? Title { get; set; }

        [JsonPropertyName("description")]
        public string? Description { get; set; }

        [JsonPropertyName("url")]
        public string? Url { get; set; }

        [JsonPropertyName("urlToImage")]
        public string? UrlToImage { get; set; }

        [JsonPropertyName("publishedAt")]
        public DateTime PublishedAt { get; set; }

        [JsonPropertyName("content")]
        public string? Content { get; set; }
    }

    public class EnergyNews {

        [JsonPropertyName("status")]
        public string? Status { get; set; }

        [JsonPropertyName("totalResults")]
        public int TotalResults { get; set; }

        [JsonPropertyName("articles")]
        public IList<Article>? Articles { get; set; }
    }
}

Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-09-09T03:12:18.7733333+00:00

    Hello,

    You can get result correctly by adding HttpClient.DefaultRequestHeaders Property in the HttpClient.

    Then you can get the data like a web Brower.

    You can refer to the following code.

     httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
    
     var response =
         await httpClient.GetAsync(url);
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.