Xamarin.Forms中Android平台WebRequest数据获取失败求助
Your code works perfectly on Windows, but Android has a few unique network-related quirks that are likely causing this problem. Let’s walk through the most common fixes step by step:
1. Double-check Android network permissions
Android requires explicit permission to access the internet. Make sure your AndroidManifest.xml includes these lines (you can also enable them via Visual Studio’s Android Manifest project settings):
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Optional but helpful for debugging -->
2. Switch to AndroidClientHandler for better compatibility
Xamarin.Android’s default HttpClient handler can have compatibility issues on some devices. Try updating your HttpClient initialization:
private HttpClient _Client = new HttpClient(new AndroidClientHandler());
Also, go to your Android project’s Properties > Android Options > Advanced and set "HttpClient Implementation" to Android (instead of Default).
3. Force TLS 1.2 support (for older Android devices)
Devices running Android 7.0 or below don’t enable TLS 1.2 by default, and jsonplaceholder.typicode.com uses this secure protocol. Add this code to your MainActivity.cs’s OnCreate method:
protected override void OnCreate(Bundle savedInstanceState) { // Enable TLS 1.2 for secure connections ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; base.OnCreate(savedInstanceState); // Rest of your OnCreate code... }
4. Fix the async void lifecycle issue (and get better error details)
Using async void in OnAppearing can swallow exceptions or cause lifecycle conflicts. Refactor your code to use a separate async method, and print the full exception chain to see the real root cause:
protected override async void OnAppearing() { await LoadPostsAsync(); base.OnAppearing(); } private async Task LoadPostsAsync() { try { var content = await _Client.GetStringAsync(url); var post = JsonConvert.DeserializeObject<List<Post>>(content); _post = new ObservableCollection<Post>(post); Post_List.ItemsSource = _post; await DisplayAlert("content", content, "ok"); } catch (Exception ex) { // Print the full exception stack to see inner errors var currentEx = ex; while (currentEx != null) { Debug.WriteLine($"Error: {currentEx.Message}"); currentEx = currentEx.InnerException; } } }
This will show you exactly what’s going on—whether it’s a certificate issue, network timeout, or something else.
5. Handle Android 9+ cleartext traffic (if needed)
While you’re using HTTPS, if your URL ever redirects to HTTP (unlikely here, but worth checking), Android 9+ blocks plaintext traffic by default. Add this to your AndroidManifest.xml’s application tag:
android:usesCleartextTraffic="true"
Start with checking permissions and printing the full exception—those are usually the fastest ways to pinpoint the problem.
内容的提问来源于stack exchange,提问作者Henrique Marques

