Just to be clear right away this code will only work outside of your typical browser (IE, Chrome, Firefox, etc...) and is geared toward mobile development scenarios. If you want a little background on why you can read up on the topic here: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing. CRM doesn't support CORS so any attempt to authenticate through the browser fails.
This is based on the C# example I posted previously. I've previously posted this code before (here and here) but this time around I wanted to provide an example of it in use.
The code to generate the SOAP headers looks like this: