如何设置请求的超时并获取MvvmCross xamarin中HttpRequest的响应代码

时间:2017-05-28 08:03:18

标签: c# android http xamarin xamarin.android

代码我为

构建了代码
 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;
        }
    }

我想做什么

  1. 为请求设置超时
  2. 请求超时的Catch相关异常
  3. 获取请求的响应代码

2 个答案:

答案 0 :(得分:2)

这个问题与MvvmCross,Xamarin或Android无关,因为您使用的是与任何.NET应用程序相同的HTTP客户端。但是,HttpClient具有Timeout属性,您可以设置该属性以确保请求在一定时间间隔后超时。我已将GetStringAsync更改为GetAsync,因为如果请求超时,GetAsync会抛出TaskCanceledException,您可以抓住并处理。{1}} 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;
}

答案 1 :(得分:2)

可以重构此类以重用客户端,而不是为每个请求创建新实例。初始化时在客户端设置超时。

public class RestService : IRestService {
    private static HttpClient client = new HttpClient();

    static RestService() {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = TimeSpan.FromMilliseconds(Constants.DefaultTimeOut);
    }

    public async Task<StellaData> GetStellConfigData() {
        try {                
            //Add the API
            using(var response = await client.GetAsync(new Uri(Constants.mUrl))) {
                if (response.IsSuccessStatusCode) {
                    return await response.Content.ReadAsAsync<StellaData>();
                }
            }
        } catch (Exception ex) {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
        return null;
    }
}