【问题标题】:Xamarin HttpClient GetStringAsync never returnXamarin HttpClient GetStringAsync 永远不会返回
【发布时间】:2017-11-30 19:05:01
【问题描述】:

以下代码从不返回任何值,我正在研究 Xamarin Forms,并且我在 VS2017 上使用可移植类库,每当我运行应用程序时,它都会挂在这条线上
var content = await _client.GetStringAsync (_url);
并且永远不会返回在应用程序引发异常 (TaskCanceledException) 之前的任何事情 我已经搜索了 Google 并找不到任何解决方案 ...

它在 iOS 和 Android 上都不起作用,我还在 Shared 而不是 PCL 上进行了测试它也不起作用。 .. 我在所有项目(PCL、Android 和 iOS)上都安装了 Microsoft.Net.Http

我是初学者,现在正在学习使用restful api

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Posts
{
public partial class MainPage : ContentPage
{
    private const string _url ="https://jsonplaceholder.typicode.com/posts";

    private HttpClient _client = new HttpClient();

    public MainPage()
    {
        InitializeComponent();
    }

    protected override async void OnAppearing()
    {
        var content = await _client.GetStringAsync(_url);
        var posts = JsonConvert.DeserializeObject<List<Post>>(content);
        postsListView.ItemsSource = new ObservableCollection<Post>(posts);
        base.OnAppearing();
    }

    void OnAdd(object sender, EventArgs e)
    {
    }

    void OnUpdate(object sender, EventArgs e)
    {
    }

    void OnDelete(object sender, EventArgs e)
    {
    }
}

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

}

【问题讨论】:

  • 您确定您的设备/模拟器可以访问互联网吗?
  • 我放了internet权限,我没有用模拟器,我通过手机浏览器访问url进行了测试
  • 如果您可以从设备浏览器访问端点,看起来您必须使用清单文件为您的应用程序启用互联网访问:developer.xamarin.com/recipes/android/general/projects/…
  • 我已经添加了权限,但是没有用

标签: rest xamarin httpclient


【解决方案1】:

经过大量研究和测试,我发现问题在于返回给我的 Json API。我不明白的是,当我通过浏览器访问url时,json正确,在VS中解析json时没有任何错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2019-11-15
    • 2011-07-25
    • 1970-01-01
    • 2012-10-02
    • 2013-02-18
    相关资源
    最近更新 更多