简体   繁体   中英

Xamarin Form HttpClient Stuck

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

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

Thanks!

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).

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

...

}

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

Hope this helps.

I have the same problem. I fixed it by:

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

you can try it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM