简体   繁体   中英

Consuming a Web API in Xamarin

I've created a Web API in ASP.NET that is hosted on a web server. This Web API accesses a table in SQL Server where I have a table called Products with Id, ProductName, Description and Price , I did the tests via Postman and it is working correctly, but when I try to consume the method to bring a specific product via Xamarin application, I get the following error message in break mode:

System.Net.Http.HttpRequestException: Timeout exceeded getting exception details

public class DataService
{

    public async Task<List<Product>> GetProductAsync(string ProductName)
    {

        using (var client = new HttpClient())
        {

            string url = "http://ProductsAPI.hostname.com/api";

            try
            {

               var uri = url + "/" + ProductName.ToString();
               HttpResponseMessage response = await client.GetAsync(uri);
               var ProductJsonString = awaitresponse.Content.ReadAsStringAsync();
               var Product = JsonConvert.DeserializeObject<List<Product>>(ProductJsonString);

               return Product;

            }

            catch (Exception ex)

            {
                throw ex;
            }

        }

    }

}

Here's what I've used in the past:

public string GetAPIJsonAsync(string URL)
    {
        using (WebClient wc = new WebClient())
        {
            return wc.DownloadString(URL);
        }
    }

This would return the raw JSON to whoever called it, and I would then convert it to the desirable object.

If you increase the timeout of the HttpClient, does it return more information?

Also, try Refit It does all the work for you, including deserializing into json.

This Works Perfectly for me

  public static async Task<List<BranchMasterModel>> GetBranchList(int city)
    {
        var client = new HttpClient(new NativeMessageHandler());

        client.BaseAddress = new Uri(UrlAdd);//("http://192.168.101.119:8475/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "AuthToken"));
        var result = await client.GetAsync("api/Master/V2/Branch/"+city);
        string branch = await result.Content.ReadAsStringAsync();
        var branches = JsonConvert.DeserializeObject<List<BranchMasterModel>>(branch);
        return branches;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM