[英]Xamarin Form HttpClient Stuck
I'm trying to get response from soundcloud API. 我正在尝试从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
. 但这卡在
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. 我只是在PCL中使用了您的代码,仅更改了满足iOS ATS要求的URL(到
https
),并从异步方法中对其进行了调用。 Seems to work fine running on iOS device. 似乎可以在iOS设备上正常运行。 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中抓取了对
Microsoft.Net.Http
引用,并在PCL 和特定于平台的项目 (通过NuGet)中抓取了对ModernHttpClient
引用。
Your code in some PCL view model class: 您在某些PCL视图模型类中的代码:
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: 然后在实例化并使用视图模型实例的PCL页面类中:
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. 你可以试试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.