Today we have another sample MonoTouch program. This little program performs a synchronous web request. Though we’re using a UIWebView to display the results of the web request, the focus is on one way to perform a synchronous web request in MonoTouch. Note that HttpWebRequst and HttpWebResponse are .Net classes; don’t be looking in the Apple iPhone developer pages to find their descriptions.

Please do yourself and your iPhone users a favor: don’t use this technique except in a separate thread. If you do this on the main UI thread, you’ll lock it up until you get the response or it times out.

More details on building the main application and controller are available on the MonoTouch site, including sample programs and tutorials.

Update 10/10/09: Fixed code display.

Here’s the sample code:

[sourcecode language=”csharp”] /* Copyright (c) 2009, Terry Westley

Copying and distribution of this file, with or without modification, are permitted in any medium without royalty. This file is offered as-is, without any warranty. */

using System; using System.Drawing; using System.IO; using System.Net; using System.Text;

using MonoTouch.Foundation; using MonoTouch.UIKit;

namespace MT_SampleSyncWebRequest { public class Application { static void Main (string[] args) { UIApplication.Main (args, null, “AppController”); } }

[Register (“AppController”)] public class AppController : UIApplicationDelegate { UIWindow window;

public override bool FinishedLaunching ( UIApplication app, NSDictionary options) { // Create the main view controller var vc = new MainViewController ();

// Create the main window and add main view // controller as a subview window = new UIWindow ( UIScreen.MainScreen.Bounds); window.AddSubview(vc.View);

window.MakeKeyAndVisible (); return true; }

// This method is required in iPhoneOS 3.0 public override void OnActivated ( UIApplication application) { } }

[Register] public class MainViewController : UIViewController { private UIWebView webView;

public override void ViewDidLoad () { base.ViewDidLoad ();

webView = new UIWebView (new RectangleF ( 0, 0, this.View.Frame.Width, this.View.Frame.Height)); this.View.AddSubview (webView);

string url = “http://www.wolframalpha.com/iphone/”; Uri uri = new Uri (url);

// HttpWebRequest StringBuilder pageContent = new StringBuilder(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create (uri); request.Method = “GET”;

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader( response.GetResponseStream(), Encoding.UTF8); string line; while ((line = sr.ReadLine ()) != null) { pageContent.Append (line); } sr.Close (); response.Close (); } catch (Exception ex) { Console.WriteLine (ex); }

webView.LoadHtmlString( pageContent.ToString(), new NSUrl(url)); Console.WriteLine(“Hey, switch to Simulator now”); } } } [/sourcecode]

Updated: