You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms跨iOS/Android向Web API传数据及Android报错处理

Hey there! Let’s break down your problem into two parts: fixing that annoying Android build error, and replacing your outdated WebRequest code with a better cross-platform solution.

Fixing the Android "ResolveLibraryProjectImports" Build Error

That error about missing formsviewgroup.jar is almost always related to cached build files or mismatched dependencies. Try these steps in order:

  • Clean and rebuild your entire solution: In Visual Studio, go to Build > Clean Solution, then Build > Rebuild Solution. Old cached files often cause weird cross-platform build glitches, and this clears them out.
  • Delete the Android project's obj/bin folders: Navigate to your Klokkie.Android project directory, manually delete the obj and bin folders, then restart Visual Studio and rebuild. This removes any corrupted cached library files (like the missing jar mentioned in the error).
  • Sync Xamarin.Forms NuGet versions: Make sure your iOS and Android projects are using the exact same version of the Xamarin.Forms NuGet package. Version mismatches are a common culprit for cross-platform build failures. Head to the NuGet Package Manager to update or align versions across all projects.
  • Verify Android SDK setup: Check that your Visual Studio has the correct Android SDK version installed, and that your Android project's target framework matches. Go to Project Properties > Application to check the target framework, then use Tools > Android > Android SDK Manager to confirm the corresponding SDK is installed.
Better Cross-Platform Code for Web API Requests

Your current WebRequest code is outdated, and manually concatenating JSON is error-prone (think missing quotes, type mismatches). Instead, use HttpClient—it's the recommended HTTP client for .NET, works seamlessly on both iOS and Android, and pairs great with JSON serialization libraries to clean up your code.

Step 1: Add NuGet Packages (if needed)

  • If using Newtonsoft.Json: Install the Newtonsoft.Json NuGet package to your shared project (or both iOS/Android projects).
  • If using System.Text.Json: This is built into newer Xamarin.Forms versions, so no extra installation is needed.

Step 2: Create a Reusable API Service

Put this in your shared project to keep code DRY across platforms:

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Uncomment if using Newtonsoft.Json
// using System.Text.Json; // Uncomment if using System.Text.Json

public class ApiService
{
    private readonly HttpClient _httpClient;

    public ApiService()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new System.Uri("https://your-api-base-url.com/"); // Replace with your API base URL
        _httpClient.DefaultRequestHeaders.Accept.Add(
            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> PostKlokEntryAsync(int klokId, string reason, string inOut)
    {
        // Create a strongly-typed object to serialize (avoids manual JSON mess)
        var klokEntry = new 
        {
            Klok_id = klokId,
            Reden = reason,
            InUit = inOut
        };

        // Serialize the object to JSON
        string jsonContent;
        // Option 1: Newtonsoft.Json
        jsonContent = JsonConvert.SerializeObject(klokEntry);
        // Option 2: System.Text.Json
        // jsonContent = System.Text.Json.JsonSerializer.Serialize(klokEntry);

        var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

        // Send the POST request
        var response = await _httpClient.PostAsync("api/klok-entries", requestContent); // Replace with your API endpoint

        // Ensure the request succeeded (throws an exception for 4xx/5xx status codes)
        response.EnsureSuccessStatusCode();

        // Read and return the API's response
        return await response.Content.ReadAsStringAsync();
    }
}

Step 3: Use the Service in Your UI Code

Call the service from your Xamarin.Forms pages using async/await to avoid blocking the UI:

var apiService = new ApiService();
try
{
    var response = await apiService.PostKlokEntryAsync(10, "DIENST", "U");
    // Handle the successful response here (parse JSON, show success message, etc.)
}
catch (HttpRequestException ex)
{
    // Handle errors like network issues or API errors
    Console.WriteLine($"Request failed: {ex.Message}");
    // Show an error message to the user if needed
}

Why This Is Better

  • Cross-platform reliability: HttpClient is fully supported on both iOS and Android, no more platform-specific bugs with old WebRequest.
  • Async/await support: Keeps your UI responsive instead of freezing during network calls.
  • No manual JSON: Serializing objects automatically eliminates typos and formatting errors.
  • Clean, maintainable code: Centralizing API logic in a service makes it easier to update or reuse across your app.

内容的提问来源于stack exchange,提问作者Koen Lievense

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:08