如何在应用程序中使用来自网址的数据

时间:2019-05-14 12:00:16

标签: mvvm service xamarin.forms

我正在尝试使用服务从url获取一些json文件,并将其显示在我的应用程序中。 这是我的代码现在的样子...

型号:

public class IrrigNetModel
{
    public int Id { get; set; }
    public string Message { get; set; }
    public DateTime Date { get; set; }
    public string DateText { get; set; }
    public int StationId { get; set; }
    public string StationName { get; set; }
    public float StationLongitude { get; set; }
    public float StationLatitude { get; set; }
    public int ServiceId { get; set; }
    public string ServiceName { get; set; }
}

查看:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class IrrigNetPage : ContentPage
{
    public IrrigNetPage()
    {
        InitializeComponent();
        BindingContext = new IrrigNetViewModel();
    }
}

ViewModel

        //ServicesModel irrigNetModel = new ServicesModel()
        //{
        //    Id = 1,
        //    Message = "sample string 2",
        //    Date = DateTime.Now,
        //    DateText = "sample string 4",
        //    StationId = 5,
        //    StationName = "sample string 6",
        //    StationLongitude = 1,
        //    StationLatitude = 1,
        //    ServiceId = 7,
        //    ServiceName = "sample string 8"
        //};

        //public IrrigNetViewModel(ServicesModel services)
        //{
        //    irrigNetModel.Id = services.Id;
        //    irrigNetModel.Message = services.Message;
        //    irrigNetModel.Date = services.Date;
        //    irrigNetModel.DateText = services.DateText;
        //    irrigNetModel.StationId = services.StationId;
        //    irrigNetModel.StationName = services.StationName;
        //    irrigNetModel.StationLongitude = services.StationLongitude;
        //    irrigNetModel.StationLatitude = services.StationLatitude;
        //    irrigNetModel.ServiceId = services.ServiceId;
        //    irrigNetModel.ServiceName = services.ServiceName;
        //}


        public ObservableCollection<IrrigNetModel> IrrigNetCollection { get; set; } = new ObservableCollection<IrrigNetModel>
        {
            new IrrigNetModel
            {
                StationId = 1,
                StationName = "Krakatosia",
                Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur scelerisque a lorem sit amet mattis.",
                DateText = "21.07.2012."
            }
        };

        public IrrigNetViewModel()
        {
            IrrigNetService.GetServices("TOKEN", "sr");
            TabTappedCommand = new Command((tabName) => OnTapClicked(tabName.ToString()));
            HideListOnTapCommand = new Command(HideListOnTap);
            IrrigNetModel model = new IrrigNetModel();
            //ShowIrrigNetDetailPageCommand = new Command(ShowDetailPage);
            var irrigNetModel = new IrrigNetModel
            {
                //StationName = model.StationName,
                //Message = model.Message,
                //DateText = model.DateText
                StationId = 1,
                Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur scelerisque a lorem sit amet mattis.",
                DateText = "03.07.2021."
            };
            IrrigNetCollection.Add(irrigNetModel);
        }

在ViewModel中,您可以看到我试图显示的所有数据,但它们都是经过硬编码的,用于测试目的(只是为了查看我的页面在某些数据下的样子)。

当然,这是我的服务:

class IrrigNetService
    {
        public static async Task<IrrigNetModel> GetServices(string token, string lngCode)
        {
            string url = DataURL.BASE_URL + "ekonetmobile/getlistnotifications?lngCode={" + lngCode + "}";
            IrrigNetModel model = new IrrigNetModel();
            try
            {
                using(var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Culture", LocalData.Lang);

                    string content = Newtonsoft.Json.JsonConvert.SerializeObject(model);
                    HttpResponseMessage result = await client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json"));
                    if (result.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        string resultContent = await result.Content.ReadAsStringAsync();
                        model = (IrrigNetModel)Newtonsoft.Json.JsonConvert.DeserializeObject(resultContent.ToString(), typeof(IrrigNetModel)); 
                    }
                    else if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {

                    }
                }
            }
            catch (Exception)
            {
                model = null;
            }
            return model;
        }
    }
POST api/ekonetmobile/getlistnotifications?lngCode={lngCode}


Currently my service show:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: no-cache
Date: Tue, 14 May 2019 12:03:14 GMT
Pragma: no-cache
Server: Microsoft-IIS/8.5
WWW-Authenticate: Bearer
X-Android-Received-Millis: 1557835393828
X-Android-Response-Source: NETWORK 401
X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1557835393651
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 61
Content-Type: application/json; charset=utf-8
Expires: -1
}}

所以,重点是在json的'StationName','Message','DateText'等中设置值,而不是“ Lorem ipsum dolor sit amet ...”和其他常量值...

1 个答案:

答案 0 :(得分:0)

解决方案: 我创建了新课程:

public class LocalData
{
    public static string Token
    {
        get
        {
            return CrossSecureStorage.Current.GetValue("TOKEN");
        }
        set
        {
            CrossSecureStorage.Current.SetValue("TOKEN", value);
        }
    }
}

然后,像这样编辑LoginViewModel:

class LoginViewModel
    {
        public string Username { get; set; }
        public string Password { get; set; }

    public Command LoginCommand => new Command(async () =>
    {
        LoginModel model = new LoginModel(Username, Password);

        if (model.CheckInformation())
        {
            AccountResponseModel response = await LoginService.Login(model);
            if (!string.IsNullOrEmpty(response.Token))
            {
                await Application.Current.MainPage.DisplayAlert("Prijavljivanje", "Uspešno ste se prijavili", "OK.");
                LocalData.Token = response.Token;
                Application.Current.MainPage = new AgroNetMasterPage();

            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Prijavljivanje", "Prijava neuspešna. Netačno ime ili lozinka", "OK.");
            }
        }
        else
        {
            await Application.Current.MainPage.DisplayAlert("Prijavljivanje", "Prijava neuspešna. Netačno ime ili lozinka", "OK.");
        }
    });
}

您可以通过zu在LocalData中设置令牌

LocalData.Token = response.Token;

此外,这是AccountResponseModel:

public class AccountResponseModel
    {
        public string Token { get; set; }
        public string RoleId { get; set; }
        public string UserId { get; set; }
    }

毕竟我的服务现在看起来有点不同:

class IrrigNetService
{

    public static async Task<IrrigNetModel> GetServices(string token, string lngCode)
    {
        IrrigNetModel model = new IrrigNetModel();
        try
        {
            string URL = DataURL.BASE_URL + "agronetmobile/getlistnotifications?lngCode=" + lngCode;
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(model);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                //client.DefaultRequestHeaders.TryAddWithoutValidation("Culture", LocalData.Lang);

                HttpResponseMessage result = await client.PostAsync(URL, new StringContent(content, Encoding.UTF8, "application/json"));                    
                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {

                    string resultContent = await result.Content.ReadAsStringAsync();
                    model = (IrrigNetModel)Newtonsoft.Json.JsonConvert.DeserializeObject(resultContent, typeof(IrrigNetModel));

                }
                else if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    //
                }
            }
        }
        catch (Exception ex)
        {
            model = null;
        }
        return model;
    }
}