2017-08-13 21 views
0

我想做一個基本的android應用程序,但我不能趕上WebException。當我嘗試連接的服務器打開時,一切正常,但是當我關閉服務器時,我的Android應用程序就會掛起。我嘗試了Windows Form Application中的代碼,它正在工作,異常被捕獲,但在Xamarin中,它只是掛起。請幫幫我。WebException不被捕獲在xamarin android

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

遠程類

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

回答

0

我建議你使用Xamarin推薦的做事方式 - 使用HttpClient的。這可能不是你之前在Forms開發中使用過的東西,但是這是一個更高級別的API,它允許你做同樣的事情,但是沒有很多額外的代碼來編寫。

Xamarin大學教人們使用modernhttpclient nuget包,並像下面一樣實現你的android代碼。 nuget包會讓平臺(在這種情況下爲android)自動使用優化的庫來執行網絡調用。

示例代碼從一個API,錯誤處理和遠程對象的反序列化得到一些東西:

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

注意:您需要Microsoft.AspNet.WebApi.Client NuGet包。

+0

和以前一樣,異常沒有得到捕獲,如果服務器處於脫機狀態,這個工作正常,否則我的應用崩潰了 – paulharley421

+0

你確定你在異步塊中調用了上面的代碼嗎?嘗試抓住「GetAsync」應該捕獲錯誤 - 我剛剛在一個香草android應用程序中轉載了這個。另外請確保您安裝了Microsoft.AspNet.WebApi.Client nuget軟件包...! –