Xamarin 表单 HttpClient 卡住了

Xamarin Form HttpClient Stuck

我正在尝试从 soundcloud API 获得响应。这是我的代码。

public static async Task<string> GetTheGoodStuff()
  {
     var client = new HttpClient(new NativeMessageHandler());
     var response = await client.GetAsync("http://api.soundcloud.com/playlists?client_id=17ecae4040e171a5cf25dd0f1ee47f7e&limit=1");
     var responseString = response.Content.ReadAsStringAsync().Result;
     return responseString;
   }

但卡在 var response = await client.GetAsync。我该如何解决这个问题?

谢谢!

我只是在 PCL 中使用了您的代码,我唯一更改的是 url(改为 https)以满足 iOS ATS 要求,并调用它来自异步方法。似乎在 iOS 设备上工作正常 运行。我确实在 PCL 中引用了 Microsoft.Net.Http,在 PCL 中引用了 ModernHttpClient,在特定于平台的项目中引用了 (通过NuGet).

您在某些 PCL 视图模型中的代码 class:

using System.Net.Http;
using System.Threading.Tasks;
using ModernHttpClient;

public class ItemsViewModel
{

...

    public async Task<string> GetPlaylist()
    {
        // Use https to satisfy iOS ATS requirements.
        var client = new HttpClient(new NativeMessageHandler());
        var response = await client.GetAsync("https://api.soundcloud.com/playlists?client_id=17ecae4040e171a5cf25dd0f1ee47f7e&limit=1");
        var responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    }

...

}

然后在 PCL 页面 class 中实例化并使用视图模型的实例:

public partial class ItemsPage : ContentPage
{
    public ItemsPage()
    {
        InitializeComponent();
        Vm = new ItemsViewModel();
        BindingContext = Vm;
    }

    protected override async void OnAppearing()
    {
        var playlist = await Vm.GetPlaylist();
        // Do something cool with the string, maybe some data binding.
    }

    // Public for data binding.
    public ItemsViewModel Vm { get; private set; }
}

希望这对您有所帮助。

我也遇到了同样的问题。我通过以下方式修复了它:

var response = httpClient.GetAsync(ApiUrl).ConfigureAwait(false).GetAwaiter().GetResult();

你可以试试