【问题标题】:Consuming a Web API in Xamarin在 Xamarin 中使用 Web API
【发布时间】:2018-07-05 13:47:46
【问题描述】:

我在 ASP.NET 中创建了一个托管在 Web 服务器上的 Web API。此 Web API 访问 SQL Server 中的一个表,其中我有一个名为 ProductsId, ProductName, Description and Price 的表,我通过 Postman 进行了测试,它工作正常,但是当我尝试使用该方法通过 Xamarin 带来特定产品时应用程序,我在中断模式下收到以下错误消息:

System.Net.Http.HttpRequestException: 超时获取异常详细信息

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;
            }

        }

    }

}

【问题讨论】:

  • 请求的状态码是什么? stackoverflow.com/questions/22217619/…
  • 超时不是真正的错误,它是 Visual Studio 生成的错误。请检查错误详情。
  • 我收到此消息未处理异常:System.Net.Http.HttpRequestException:发送请求时出错
  • 您是否有任何代理限制或防火墙端口阻止?
  • 可能会尝试使用 Fiddler (telerik.com/fiddler) 查看实际发出的请求并返回结果。

标签: c# xamarin xamarin.forms xamarin.android


【解决方案1】:

这是我过去使用过的:

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

这会将原始 JSON 返回给调用它的人,然后我会将其转换为所需的对象。

【讨论】:

    【解决方案2】:

    如果增加 HttpClient 的超时时间,它会返回更多信息吗?

    另外,试试Refit 它会为您完成所有工作,包括反序列化为 json。

    【讨论】:

      【解决方案3】:

      这对我来说非常有效

        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;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-05
        • 1970-01-01
        • 2021-12-26
        • 2018-12-17
        • 1970-01-01
        • 2014-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多