首页 > 解决方案 > How to consume data from url in application

问题描述

I'm trying to get some json file from url using service and show them in my application. Here's how my code looks like now...

Model:

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

View:

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

In ViewModel you can see all what I have tried to show data but currnetly it's hardcoded for testing purpose (just to see how my page looks like with some data).

And, of course here is my service:

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

So, the point is to set value in 'StationName', 'Message', 'DateText' etc, etc from json, instead of "Lorem ipsum dolor sit amet..." and other constant values...

标签: mvvmservicexamarin.forms

解决方案


解决方案: 我创建了新类:

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.");
        }
    });
}

如您所见,我在 LocalData 中设置了 Token

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

推荐阅读