我正在尝试创建一个基本的Android应用程序,但我无法抓住WebException
。当我正在尝试连接的服务器打开时,一切正常,但是当我关闭服务器时,我的Android应用程序就会挂起。我尝试了Windows窗体应用程序中的代码并且它正常工作,异常被捕获,但在Xamarin中,它只是挂起。请帮帮我。
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 :(得分:0)
我建议你使用Xamarin推荐的做事方式 - 使用HttpClient。这可能不是您之前在Forms开发中使用过的东西,但这是一个更高级别的API,它允许您执行相同操作,但不需要编写大量额外代码。
Xamarin大学教人们使用现代的httpclient nuget包,并实现你的Android代码,如下所示。 nuget包将让平台(在本例中为android)自动使用优化库来执行Web调用。
示例代码,用于从远程对象的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包。