Xamarin http webservice问题

时间:2014-11-20 07:10:04

标签: xamarin

我试图使用http请求webservice问题是,当我们发布错误的用户名和密码时,登录服务会生成异常,并且它无法在异步调用中返回任何值。

2 个答案:

答案 0 :(得分:0)

代码段有助于解决问题......

但是,使用try catch可以帮助您捕获异常并防止应用程序崩溃并相应地处理异常。

如下面的示例代码所示,我提供了输入错误的详细信息/连接问题。我执行http异步请求,然后将xml解析为我的模型,相应地处理异常

                var response = await WebRequestHelper.MakeAsyncRequest(url, content);
                if (response.IsSuccessStatusCode == true)
                {
                    Debug.WriteLine("Login Successfull" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);

                    var result = response.Content.ReadAsStringAsync().Result;
                    result = result.Replace("<xml>", "<LoginResult>").Replace("</xml>", "</LoginResult>");
                    loginResult = XMLHelper.FromXml<LoginResult>(result);

                    if (loginResult != null)
                    {
                        login.Type = ResultType.OK;
                        login.Result = loginResult;
                    }
                    else
                    {
                        login.Type = ResultType.WrongDetails;
                    }
                }
                else
                {
                    Debug.WriteLine("Login Failed" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
                    login.Type = ResultType.WrongDetails;
                }
            }

            catch (Exception ex)
            {
                login.Type = ResultType.ConnectivityProblem;
            }

网络申请

    public static async Task<HttpResponseMessage> MakeAsyncRequest(string url, Dictionary<string, string> content)
    {
        var httpClient = new HttpClient();
        httpClient.Timeout = new TimeSpan(0, 5, 0);
        httpClient.BaseAddress = new Uri(url);
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");

        if (content == null)
        {
            content = new Dictionary<string, string>();
        }

        var encodedContent = new FormUrlEncodedContent(content);

        var result = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);

        return result;

答案 1 :(得分:0)

我建议将响应包装在通用的ServiceResponse中,您可以在其中存储异常。 await方法可以包含在try / catch块中,因此可以遵循标准过程。

E.G。

public async Task<ServiceResponse<T>> PostAsync<T>(String address, object dto){
    var content = Serializer.SerializeObject (dto);
    var response = await client.PostAsync (
        address, 
        new StringContent (content));

    if (response.IsSuccessStatusCode) {
        try {
            var responseString = await response.Content.ReadAsStringAsync ();
            return new ServiceResponse<T> (Serializer.DeserializeObject<T> (responseString),
                response.StatusCode);
        } catch (Exception ex) {
            return new ServiceResponse<T> (response.StatusCode, ex);
        }
    } else {
        return new ServiceResponse<T> (response.StatusCode);
    }
}

ServiceResponse定义为:

public class ServiceResponse<T>
{
    public HttpStatusCode StatusCode { get; set;}

    public T Value { get; set;}

    public String Content { get; set;}

    public Exception Error {get;set;}

    public ServiceResponse(T value, HttpStatusCode httpStatusCode){
        this.Value = value;
        this.StatusCode = httpStatusCode;
    }

    public ServiceResponse(HttpStatusCode httpStatusCode, Exception error = null){
        this.StatusCode = httpStatusCode;
        this.Error = error;
    }
}

这将为您提供一种管理所有HTTP响应和可能发生的任何错误的简洁方法。