CodeGo.net>如何设置请求超时,并在MvvmCross xamarin中获取HttpRequest的响应代码

我为以下目的构造的代码:

 public class RestService : IRestService
    {
        public async Task<StellaData> GetStellConfigData()
        {
            try
            {   
                //Declare a Http client
                HttpClient client = new HttpClient();
                //Add a Base URl
                //client.BaseAddress = new Uri(Constants.MUrl);
                //Add the response type
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Add the API
                var response =await client.GetStringAsync(new Uri(Constants.mUrl));

                var myItems = Newtonsoft.Json.JsonConvert.DeserializeObject<StellaData>(response);
                return myItems;

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return null;
        }
    }

我正在尝试做的是:

>为请求设置超时
>与请求超时相关的异常
>获取请求的响应代码

解决方法:

这个问题确实与MvvmCross,Xamarin或Android无关,因为您使用的HTTP客户端与任何.NET应用程序中的客户端相同.尽管如此,HttpClient具有一个Timeout属性,您可以设置该属性以确保您的请求在一定间隔后超时.我将GetStringAsync更改为GetAsync,因为如果请求超时,GetAsync将抛出TaskCanceledException,您可以捕获并处理该异常. GetStringAsync将在内部处理超时,您将无法捕获该超时.我重写了您的方法来实现这一点(此示例具有30秒的超时),并将状态代码分配给变量以供您使用:

public async Task<StellaData> GetStellConfigData()
{
    try
    {
        using (var client = new HttpClient
        {
            Timeout = TimeSpan.FromMilliseconds(30000)
        })
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await client.GetAsync(new Uri(Constants.mUrl));

            HttpStatusCode statusCode = response.StatusCode;

            var myItems = Newtonsoft.Json.JsonConvert.DeserializeObject<StellaData>(await response.Content.ReadAsStringAsync());
            return myItems;
        }

    }
    catch (TaskCanceledException tcex)
    {
        // The request timed out
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }

    return null;
}
上一篇:C#-使用Xamarin将数据从iPhone传输到Apple Watch


下一篇:CodeGo.net>如何在Xamarin.Forms中自定义TabbedPage的选项卡项?