Reputation: 55
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!
Upvotes: 2
Views: 5098
Reputation: 544
I have the same problem. I fixed it by:
var response = httpClient.GetAsync(ApiUrl).ConfigureAwait(false).GetAwaiter().GetResult();
you can try it.
Upvotes: 1
Reputation: 2363
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.
Upvotes: 1