从HTTP请求Xamarin获取数据

时间:2018-07-25 07:52:22

标签: rest xamarin xamarin.forms httprequest

我想从HTTPWebRequest获取数据并将数据传递到我的同步页面。我是MVVM的新手,所以我不知道我是否正确,但是到目前为止,我可以检查是否有结果。我尝试观看了许多视频教程和论坛,但仍然找不到所需的内容。我希望你们对我有答案。我已经为此努力了一个星期。

我的项目流程: -正确时,用户将登录。该用户将被重定向到我的同步页面,该页面将从我的服务器获取所有用户数据,并将数据插入SQLite数据库。

我的问题是:
1。如何从HTTPWebRequest获取数据和特定数据?
2.我的HTTPWebRequest服务正确​​吗?
3.我的MVVM是否正确?
4.我到下一页的导航是否正确?

我的代码:

LoginPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBSMobileApplication.Data;
using TBSMobileApplication.ViewModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TBSMobileApplication.View
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        public LoginPageViewModel loginModel;
        public LoginPage ()
        {
            InitializeComponent ();
            BindingContext = new LoginPageViewModel();
            MessagingCenter.Subscribe<LoginPageViewModel,string>(this, "Login Alert", (sender,Username) =>
            {
                DisplayAlert("Login Error", "Please fill-up the form", "Ok");
            });

            MessagingCenter.Subscribe<LoginPageViewModel, string>(this, "Connected", (sender, Username) =>
            {
                DisplayAlert("Connection Info", "Connected", "Ok");
            });

            MessagingCenter.Subscribe<LoginPageViewModel, string>(this, "Not Connected", (sender, Username) =>
            {
                DisplayAlert("Connection Info", "Not Connected", "Ok");
            }); 

            MessagingCenter.Subscribe<LoginPageViewModel, string>(this, "Http", (sender, Username) =>
            {
                DisplayAlert("Login Error", "Username or Password is incorrect", "Ok");
            });

            entUsername.Completed += (object sender, EventArgs e) =>
            {
                entPassword.Focus();
            };
        }

        protected async Task OnAppearingAsync()
        {
            var db = DependencyService.Get<ISQLiteDB>();
            var conn = db.GetConnection();

            if (conn != null)
            {
                await conn.CreateTableAsync<UserTable>();
                await conn.CreateTableAsync<RetailerTable>();
                await conn.CreateTableAsync<ContactsTable>();
            }

            base.OnAppearing();
        }
    }
}

LoginPageViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace TBSMobileApplication.ViewModel
{
    public class LoginPageViewModel : INotifyPropertyChanged
    {
        void OnProperyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string username;
        public string password;

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnProperyChanged(nameof(Username));
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnProperyChanged(nameof(Password));
            }
        }

        public ICommand LoginCommand { get; set; }

        public LoginPageViewModel()
        {
            LoginCommand = new Command(OnLogin);
        }

        public void OnLogin()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                MessagingCenter.Send(this, "Login Alert", Username);
            }
            else
            {
                var current = Connectivity.NetworkAccess;

                if (current == NetworkAccess.Internet)
                {
                    var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
                    var request = HttpWebRequest.Create(string.Format(@link));
                    request.ContentType = "application/json";
                    request.Method = "GET";

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                var content = reader.ReadToEnd();

                                if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
                                {
                                    MessagingCenter.Send(this, "Http", Username);
                                }
                                else
                                {
                                    App.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true);
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessagingCenter.Send(this, "Not Connected", Username);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

0 个答案:

没有答案