I have tried this code in a normal C# app and it works fine. In monodroid, it completely bugs out (in other words, not even the 开发者_如何学Ctry-catch works) when I try to READ from the stream (or the base stream) in ANY way. Please help:
try
{
WebRequest request = WebRequest.Create(string.Format("http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=false", "35.245619","-98.276369"));
WebResponse wresponse = request.GetResponse();
using (StreamReader sr = new StreamReader(wresponse.GetResponseStream()))
{
RunOnUiThread(() => _debug.Text = (sr.ReadToEnd()).ToString());
}
wresponse.Close();
}
catch (Exception ex)
{
RunOnUiThread(() => _debug.Text = string.Format("Exception: ", ex.Message));
}
_debug is a TextView object on my UI.
How about this way?
try
{
WebRequest request = WebRequest.Create(string.Format("http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=false", "35.245619","-98.276369"));
WebResponse wresponse = request.GetResponse();
var resp=string.Empty;
using (StreamReader sr = new StreamReader(wresponse.GetResponseStream()))
{
resp=sr.ReadToEnd().ToString();
}
wresponse.Close();
RunOnUiThread(() => _debug.Text = resp);
}
catch (Exception ex)
{
RunOnUiThread(() => _debug.Text = string.Format("Exception: ", ex.Message));
}
Sound has provided the answer. That should work. I'll just explain the reason a bit.
From your code, it seems like you are doing the HTTP request on a background thread. That's why you need to do the RunOnUiThread. This is a very good approach.
However, RunOnUiThread does not guarantee that the code will be executed immediately on the UI thread. It merely posts a message to the UI thread run loop. And when the UI thread gets a chance, it will execute it.
What this essentially means is that "wresponse.close()" will probably run before "resp=sr.ReadToEnd().ToString()". Since the response is closed, any attempt to read from it will cause an error. But the error happens on the UI thread since the read attempt will be on UI thread. Thats why your try/catch block doesn't function.
In Sound's code, this problem is eliminated. As a side note, this code is also much better performing since the actual reading of bytes is offloaded to the worker thread, so your UI thread will be much more responsive.
精彩评论