WinJS helper for converting from WinJS.xhr to HttpClient
This post isn’t strictly part of the “Building Great Apps” series, but it will be referenced there, and since someone was asking about this helper on Twitter I decided to go ahead and post it here.
In Windows 8.1, a new WinRT API was introduced for making HTTP requests. The main runtime class used is Windows.Web.Http.HttpClient.
There are several ways in which this is superior to the standard XmlHttpRequest interface. Unfortunately, for those using WinJS.xhr() today, converting your code to use HttpClient is non-trivial.
In my case, I had to convert all of my XHR calls to use HttpClient to work around a bug in XHR… A deadlock which occurs in IE/Windows’ XHR implementation when used simultaneously from multiple threads (i.e. the UI thread and one or more WebWorkers). I reported the issue to Microsoft and they identified the source of the bug, but rather than wait for them to issue a fix for it, I decided to migrate all my code to HttpClient which doesn’t have this problem.
In some cases, like my Twitter Stream API consumer, I rewrote the whole thing using HttpClient, because it made more sense, and the new implementation is superior in several ways. The original implementation did use WinJS.xhr, but it was a heavily… customized usage.
However, the rest of my code used WinJS.xhr in pretty standard ways. Rather than rewrite any of it, I decided to just create a drop-in replacement for WinJS.xhr which wraps HttpClient. Better yet, it should detect when WinRT is not available (i.e. if running on Windows Phone 8, iOS, etc), and fall back to the regular WinJS.xhr implementation.
I posted the helper up here as a GitHub Gist:
https://gist.github.com/BrandonLive/8641828
To use it, include that file in your project, and then replace calls to WinJS.xhr with BrandonJS.xhr.
One caveat is that I couldn’t find a way to inspect a JavaScript multipart FormData object in order to build the equivalent HttpMultipartFormDataContent representation. You should still be able to use the helper, you’ll just need to create one of those instead of a FormData object and pass that as the request data in its place.
If you find any problems or want to submit any improvements, please do so on the Gist page!
Trackbacks & Pingbacks
Comments are closed.