Xamarin : How to call API POST method




Xamarin : API call



How to consume API method in xamarin application ? 

I tried on google but couldn't find proper example. I got help of my friend who have knowledge of xamarin and some help from google, and created successful demo, which I am sharing with you.

Steps:
  1. First check that API is working or not
  2. Install "newtonsoft json" from NuGet package manager


Design 


<Grid>



    <Grid.RowDefinitions>

      <RowDefinition Height="50"></RowDefinition>

      <RowDefinition Height="50"></RowDefinition>

      <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"></ColumnDefinition>      
    </Grid.ColumnDefinitions>

    <Button Text="Get Data"
            Clicked="OnGetDataButtonClicked"
            Grid.Row="0"
            Grid.Column="0"></Button>
    <Label x:Name="lblMsg"
           Grid.Row="1"
           Grid.Column="0"></Label>

    <ListView x:Name="MainList"  ItemTapped="OnTapped" Grid.Row="2" Grid.Column="0"> 
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Orientation="Horizontal">
              <Label Text="{Binding EmailId}"></Label> 
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    
  </Grid>


Code

async void OnGetDataButtonClicked(object sender, EventArgs e)
        {
            try
            {
                HttpClient client = new HttpClient();

                string requestPayload = @"{
""UserId"": ""123"",
""dataTableCommon"":{
""param"" :{""Start"": ""21"",
""Length"": ""10"",
""Draw"" :""1""}
}
}";
                var response = await client.PostAsync("http://Domainname/DemoAPI/API/User/GetUsersList", 
new StringContent(requestPayload, Encoding.UTF8, "application/json"));

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var json = await response.Content.ReadAsStringAsync();
   
                    //Here you need to create class for output results
    // To generate class, you can use http://json2csharp.com

                    var results = JsonConvert.DeserializeObject<RootObject>(json);

                    MainList.ItemsSource = results.data;                    
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
            }            
        }

        void OnTapped(object sender, ItemTappedEventArgs e)
        {
            var selected = e.Item as Users;

            DisplayAlert("Name", selected.FirstName + " " + selected.LastName, "Okay");
        }


Generate Class

    // To generate class, you can use http://json2csharp.com

    

    public class Users

    {

        public string UserId { get; set; }    

        public string FirstName { get; set; }

        public string LastName { get; set; }
        public string EmailId { get; set; }
    }

    public class RootObject
    {        
        public List<Users> data { get; set; } 
    }


Output


























































I hope, you like the article !!! ENJOY !!!



No comments:

Post a Comment