简体   繁体   中英

WebException not being catch in xamarin android

I'm trying to make a basic android app, but I can't catch WebException . When the server that I'm trying to connect is on, everything works well, but when I turn off the server, my android app just hangs. I tried the code in Windows Form Application and it was working, the exception is being caught, but in Xamarin, it just hangs. Please help me.

MainActivity.cs

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "main" layout resource
    SetContentView (Resource.Layout.Main);

    Button btn1 = FindViewById<Button>(Resource.Id.button1);

    btn1.Click += (object sender, EventArgs e) =>
    {
        var result = Remote.Connect();
        if(result == WebStatus.Authenticated)
        {
            Toast.MakeText(this, "Works!", ToastLength.Short).Show();
        }
        else if(result == WebStatus.Unauthorized)
        {
            Toast.MakeText(this, "Unauthorized", ToastLength.Short).Show();
        }
        else
        {
            Toast.MakeText(this, "Something went wrong!", ToastLength.Short).Show();
        }
    };
}

Remote Class

public static WebStatus Connect()
{
    // some code

    WebRequest request = WebRequest.Create(url);

    try
    {
        using (WebResponse response = request.GetResponse())
        {
            return WebStatus.Authenticated;
        }
    }
    catch(WebException e)
    {
        using (WebResponse response = e.Response)
        {
            WebStatus status = new WebStatus();
            HttpWebResponse httpResponse = (HttpWebResponse)response;
            if (httpResponse != null)
            {
                switch (httpResponse.StatusCode)
                {
                    case HttpStatusCode.Unauthorized:
                        status = WebStatus.Unauthorized;
                        break;
                    case HttpStatusCode.NotFound:
                        status = WebStatus.Error;
                        break;
                    default:
                        status = WebStatus.Error;
                        break;
                }
            }

            return status;
        }
    }
}

I'd suggest you use the Xamarin recommended way of doing things - using the HttpClient. This might not be something you've used before in Forms development but this is a higher level api that allows you to do the same, but without a lot of the extra code to write.

Xamarin University teaches people to use the modernhttpclient nuget package, and implement your android code like below. The nuget package will let the platform (android in this case) automatically use optimized libraries to perform web calls.

Sample code to get some stuff from an api, error handling, and deserialization of your remote object:

var httpClient =  new HttpClient(new NativeMessageHandler());
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var responseMessage = await httpClient.GetAsync("some/api/endpoint/here");
if (!responseMessage.IsSuccessStatusCode)
{
    if (responseMessage.IsUnauthorized()) { // some handling here }
}
// time to get the result
var res = await responseMessage.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<Object>(res);

Note: You'll need the Microsoft.AspNet.WebApi.Client nuget package.

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