Monotouch/C# version of "stringWithContentsOfUrl"
I'm trying to convert a piece of Objective-C code into C# for use with Monotouch and I have no idea what to use to replace stringWithContentsOfUrl
Should I use something like:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.helephant.com");
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCod开发者_高级运维e == HttpStatusCode.OK &&
response.ContentLength > 0){
TextReader reader = new StreamReader(response.GetResponseStream());
string text = reader.ReadToEnd();
Console.Write(text);
}
Is that even safe to use in MonoTouch? Will it work for the iPhone?
For quick jobs, you can use the simpler WebClient.
Just do this:
var web = new System.Net.WebClient ();
var result = web.DownloadString ("http://www.google.com");
There are various helper methods like the above in WebClient that allow you to download raw data or download straight to a file. Additionally, you can use the "Async" versions of those methods to have the data be downloaded asynchronously and be notified when the download completes:
web.DownloadStringCompleted += delegate (object sender, DownloadStringCompletedEventArgs e){
Console.WriteLine ("Got {0}", e.Result);
}
web.DownloadStringAsync ("http://www.google.com");
If you are using the Async variants, remember that you cant invoke any UI methods directly as UIKit is not a toolkit that supports being accessed from multiple threads. You must use NSObject.InvokeOnMainThread to ensure that the code you call is invoked in the proper thread:
web.DownloadStringCompleted += delegate (object sender, DownloadStringCompletedEventArgs e){
label.InvokeOnMainThread (delegate { label.Text = e.Result; });
}
web.DownloadStringAsync ("http://www.google.com");
Looks fine to me. I've got some code I hacked together for something similar a while back, which works just fine.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (tmpMPURL);
request.Method = "GET";
WebResponse response = request.GetResponse ();
StreamReader reader = new StreamReader (response.GetResponseStream (),Encoding.GetEncoding("iso-8859-1"));
string responseString = reader.ReadToEnd ();
reader.Close ();
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml (responseString);
精彩评论