本文介绍了Xamarin表格HttpClient卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get response from soundcloud API. Here is my code.

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上.我该如何解决?

But it's stucks on var response = await client.GetAsync. How can I fix this?

谢谢!

推荐答案

我只是在PCL中使用了您的代码,唯一更改的是满足iOS ATS要求的URL(至https),并从异步方法.似乎可以在iOS设备上正常运行.我确实在PCL中获取了Microsoft.Net.Http的引用,并且在PCL 和特定于平台的项目中获得了ModernHttpClient的引用(通过NuGet).

I did just use your code in a PCL, only thing I changed is the url (to https) to satisfy iOS ATS requirements, and called it from an async method. Seems to work fine running on iOS device. I did grab references to Microsoft.Net.Http in the PCL, and ModernHttpClient in the PCL and in the platform-specific projects (via NuGet).

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

Your code in some PCL view model 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页面类中实例化并使用视图模型的实例:

Then in a PCL page class that instantiates and uses an instance of the view model:

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; }
}

希望这会有所帮助.

这篇关于Xamarin表格HttpClient卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 23:24