CFNetwork-powered HttpClient

Newer versions of .NET introduced a new Http client API: HttpClient. This new API is designed to integrate naturally with C# async language extension. Some of its virtues are described in Henrik's blog post.

While HttpClient by default uses the .NET framework's HttpWebRequest for actually connecting to the server, the API was designed to allow other implementations of the HTTP stack to be used instead.

With both the beta versions of MonoTouch and the upcoming Xamarin.Mac, you can now use CFNetwork as your HTTP transport. To do this, all you have to do is change your instantiation from:

var client = new HttpClient ();

To:

var client = new HttpClient (CFNetworkHandler ());

Using CFNetwork for your http client has the following differences from HttpWebRequest:

  • On iOS, CFNetwork will automatically turn on the phone's radio if it is off before starting the HTTP request. This means that you no longer need to manually use the StartWWAN methods.
  • Connection pooling is managed by CFNetwork as opposed to the settings in .NET's stack.
  • Will automatically track proxy and network settings done to iOS.
  • Operations are performed on the CFNetwork dispatch queues/threads instead of consuming threads from Mono's own managed thread pool.

In both cases, you will be able to continue using the same APIs, the only difference is in how you construct your HttpClient.

Posted on 07 Jun 2013 by Miguel de Icaza
This is a personal web page. Things said here do not represent the position of my employer.