点击按钮即可使用简单的Web服务

时间:2018-01-11 23:10:06

标签: c# json xaml xamarin xamarin.forms

我有一个简单的按钮视图。当我单击按钮时,我想调用Web服务并使用其数据。这是我的观点:

的Page1.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     x:Class="HelloWorld.Pages.Page1"
     xmlns:local="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Pages"
  <StackLayout Padding="20, 10" 
            HorizontalOptions="Center">
    <Button Clicked="B1_Clicked"
            Text="Click Me" />
  </StackLayout>
</ContentPage>

page1.xaml.cs

public page1(Models.Info info)
{
InitializeComponent();
}
private void B1_Clicked(object sender, EventArgs e)
{
     Service src = new Service();
     //how to use the data here
} 

这是service.cs

public async Task<Data> GetInfoAsync()
    { 
        DataInfo = null;
        try
        {
            var client = new HttpClient();
            HttpContent content = new StringContent("", Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.PostAsync("https://www.getdata/feed", content);
            response.EnsureSuccessStatusCode();
            string json = await response.Content.ReadAsStringAsync();

            data = JsonConvert.DeserializeObject<DataInfo>(json);
        }
        catch(Exception e)
        {
            Debug.WriteLine(e.Message.ToString());
        }
        Debug.WriteLine(data.data);
        return data.data;
    }

我想它非常简单,但我是xamarin的新手,请原谅我缺乏知识:)

2 个答案:

答案 0 :(得分:0)

您已经在调用该服务 - 您只需要从事件处理程序中调用GetInfoAsync方法

private async void B1_Clicked(object sender, EventArgs e)
{
     Service src = new Service();
     var data = await src.GetInfoAsync();
} 

答案 1 :(得分:-1)

调用Web服务的最简单方法是使用Refit。

这是一个插件,可以简化为编写Web服务而编写的代码。

它还处理从Json到类的传递头和反序列化。

There are a lot of examples at its GitHub repo here

如果您刚刚开始我会建议您使用MVVM框架,然后再使用代码。 I use FreshMvvm