c# - Monotouch/C# 版本的 "stringWithContentsOfUrl"

标签 c# objective-c xamarin.ios

我正在尝试将一段 Objective-C 代码转换为 C# 以便与 Monotouch 一起使用,但我不知道用什么来替换 stringWithContentsOfUrl 我应该使用类似的东西吗:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.helephant.com");
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK &&
    response.ContentLength > 0){
    TextReader reader = new StreamReader(response.GetResponseStream());
    string text = reader.ReadToEnd();
    Console.Write(text);
}

在 MonoTouch 中使用它是否安全?它适用于 iPhone 吗?

最佳答案

对于快速工作,您可以使用更简单的 WebClient。

只需这样做:

var web = new System.Net.WebClient ();
var result = web.DownloadString ("http://www.google.com");

在 WebClient 中有各种类似上述的帮助方法,可让您下载原始数据或直接下载到文件中。此外,您可以使用这些方法的“异步”版本来异步下载数据并在下载完成时收到通知:

web.DownloadStringCompleted += delegate (object sender, DownloadStringCompletedEventArgs e){
   Console.WriteLine ("Got {0}", e.Result);
}
web.DownloadStringAsync ("http://www.google.com");

如果您使用异步变体,请记住您不能直接调用任何 UI 方法,因为 UIKit 不是支持从多线程访问的工具包。您必须使用 NSObject.InvokeOnMainThread 来确保您调用的代码在正确的线程中被调用:

web.DownloadStringCompleted += delegate (object sender, DownloadStringCompletedEventArgs e){
   label.InvokeOnMainThread (delegate { label.Text = e.Result; });
}
web.DownloadStringAsync ("http://www.google.com");

关于c# - Monotouch/C# 版本的 "stringWithContentsOfUrl",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2492967/

相关文章:

c# - 同时等待多个任务中的一个任务

iphone - 在 UISplitViewController 中重用详细 View Controller

MonoTouch 与可移植库项目无法构建

ios - UIButton 从 Core Data 增加一个数组,从另一个类完成

iphone - 更改导航栏的字体

ios - 如何实例化 ARSCNView

c# - 无法存档我的 IOS Xamarin 项目的发布版本

c# - 使用 Bouncy CaSTLe 计算文件的哈希值

c# - 当前上下文中不存在名称 `addtaghelper`

c# - 需要有关 OOP 哲学的建议