mvvm - 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...
解决方案
解决方案: 我创建了新类:
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;
}
}
推荐阅读
- sql - 在 Datetime2 格式 DB2 上使用 Order By Desc
- ios - 强制退出应用程序在后台模式下的静默通知
- findstr - findstr: [^inverse class] 不正确的行为
- c - 在 C 中省略参数名称
- android - 为什么实际设备上的设计视图布局如此不同?
- firebase-realtime-database - 如何确定与使用量无关的“负载”每日突然出现峰值的原因?
- regex - 第 n 行的正则表达式结束
- cookies - 如何使用 urllib2 在 Python 中单独发送 cookie
- php - 在 Wordpress 简码中添加分类属性
- python - 有人可以向我解释为什么在等于 self.list 的列表上使用 pop() 也会让 self.list pop 排在最后