消费WEB API REST GET Xamarin表单 [英] Consuming WEB API REST GET Xamarin Forms
本文介绍了消费WEB API REST GET Xamarin表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在服务器上托管了一个WEB API,那里有一个带有名称和描述的Products表.我已经检查过邮递员了,这很正常,当我尝试通过Visual Studio在xamarin中实现该方法时,通过其名称记录并显示在我不能的列表视图中.有人可以在代码中帮助我
I have a WEB API hosted on a server, there I have a Products table with Name and Description.I already checked for the postman and this is ok, when I try to implement the method in xamarin by visual studio to bring a record by its name and display in a listview I can not. Could someone help me in the code
private async void GetProductByName(string Name)
{
using (var client = new HttpClient())
{
txtTest.Text = "http://www.ProdutosAPITest6.hostname.com/api/products";
var URI = txtTest.Text + "/" + Name.ToString();
var response = await client.GetAsync(URI);
string products = await response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<Produto>(products);
listview.ItemsSource = products;
}
}
<ListView x:Name="ProductsList" ItemSelected="listaProducts_ItemSelected"
BackgroundColor="Aqua" SeparatorColor="Blue">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10,10" Orientation="Horizontal">
<Label Text="{Binding Id}" HorizontalOptions="StartAndExpand"/>
<Label Text="{Binding Name}" TextColor="Blue" HorizontalOptions="Center"/>
<Label Text="{Binding Description}" HorizontalOptions="End"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
推荐答案
我对您的代码做了一些编辑.
I made a little edit to your code.
public async void GetProductByName(string Name)
{
var handler = new NativeMessageHandler();
var client = new HttpClient(handler);
client.Timeout = TimeSpan.FromSeconds(120);
txtTest.Text = "http://www.ProdutosAPITest6.hostname.com/api/products";
var URI = txtTest.Text + "/" + Name.ToString();
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(URI)
};
var response = await client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode == true)
{
var products = await response.Content.ReadAsStringAsync();
var resultModel = JsonConvert.DeserializeObject<Produto>(products);
return resultModel;
}
}
public ListView myListView { get { return ProductsList; } }
protected override async void OnAppearing()
{
var name = //pass name;
List<ProductModel> products = await GetProductByName(name);
if (products.Count() > 0)
{
myListView.ItemsSource = products;
}
base.OnAppearing();
}
我希望这对您有帮助
这篇关于消费WEB API REST GET Xamarin表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文