Your browser is very old. You might enjoy surfing the web more if you used something newer like:

Google Chrome

Even Firefox would be OK.

If you're being forced at gunpoint to use Internet Explorer, you should at least upgrade it. Version 8 is tolerable and 9 will be OK when it comes out.

Basic Authentication with Titanium.Network.HTTPClient

I’ve been trying, over the last couple of days, to figure out how to do an HTTP request with Basic Authentication using Appcelerator Titanium.

It seemed like it should be pretty easy. Just create an HTTPClient object, pass it the username and password via setBasicCredentials(), and off you go.

But it didn’t work. I got 401 – Unauthorized on every single site I tried.

Finally, after way too much research, I discovered that setBasicCredentials just doesn’t work and you have to do Basic Authentication by setting the headers yourself like this:

authstr = 'Basic ' +Titanium.Utils.base64encode(username+':'+password);
xhr.setRequestHeader('Authorization', authstr);

It’s important to note that setRequestHeader() has to be called after you’ve called open() but before you call send()

And here’s a complete function for making HTTP requests.

var httpRequest = function(params) {
    var xhr = Titanium.Network.createHTTPClient();

    xhr.onload = function() {
        if(params.hasOwnProperty('callback')) {
            if(typeof params.callback == 'function') {
                params.callback(this.responseText);
            }else {
                Ti.API.error('getXML:  Invalid callback function');
            }
        }
    };
    xhr.onerror = function() {
        Ti.API.error(this.status + ' - ' + this.statusText);
    };

    xhr.open( params.hasOwnProperty('method') ? params.method : 'GET', params.url);

    try {
        if(params.hasOwnProperty('username') && params.hasOwnProperty('password')) {
            authstr = 'Basic ' +Titanium.Utils.base64encode(params.username+':'+params.password);
            xhr.setRequestHeader('Authorization', authstr);
        }
    }catch(e) {
        Ti.API.error('Error in getXML:  ' + e.message);
    }

    xhr.send();
};

//Call it like this
httpRequest( {
        url:  'https://api.del.icio.us/v1/tags/get',
        username: 'username',
        password:  'password',
        callback:  function(resp) {
            //TODO
        }
    });

11 comments.

  1. Great solution, thank you!

    Any idea how to load https with another port than 443?

    Example URL is: https://www.astro.uni-koeln.de:8080/

    Just enter this URL won’t work :(

  2. I’m not sure if you can set the port using Network.HTTPClient.

    I wonder if CreateTCPSocket (http://developer.appcelerator.com/apidoc/desktop/latest/Titanium.Network.createTCPSocket-method) would work instead.

  3. Thanks Mark

    This is Exactly what I needed. I’d been thrashing around and only ever returning a login page before.

    Now I have a [TiBlob] to play with – yess!

    Awesome stuff,

    cheers, Chris.

  4. Hey, I need to send some xml as well as a username/password. How would I send my xml as well? in the send() method?

    This is the closest I’ve gotten so far. I’m now at least getting an xml response, just one that tells me my xml (non-existent) is formatted incorrectly.

    Thanks so much for your post!

  5. Assuming you’re using the function above, I’d think you could just do something like this:

    httpRequest( {
    url: ‘https://api.del.icio.us/v1/tags/get',
    username: ‘username’,
    password: ‘password’,
    xmlParam: ‘myxmlcontent’,
    callback: function(resp) {
    //TODO
    }
    });

  6. Is this supposed to work on the emulator?
    I keep getting “401 – undefined”
    My authstr seems ok
    Any idea?

  7. My bad, I was trying to access localhost without http://
    It does work fine

  8. Any idea whether you can do Digest Auth with Titanium’s HTTPClient?

  9. My understanding is that DigestAuth isn’t supported yet but it’s on their list for a future release.

  10. Thank you for your effort

    I would like to share my problem with you so I can get some help

    I want to open web page that needs authentication on Android but the browser do not prompt the user to enter user name and password, the page is opened directly with an error message ” unauthorized”

    I’ve tried this code

    var xhr = Ti.Network.createHTTPClient();
    xhr.open(‘GET’, URL);
    authstr = Titanium.Utils.base64encode(username + ‘:’ + pwd);
    xhr.setRequestHeader(‘Authorization’, ‘Basic ‘ + authstr);
    xhr.send();
    var webview = Titanium.UI.createWebView({url: url});
    var window = Titanium.UI.createWindow();
    window.add(webview);
    window.open({modal:true})

    but it doesn’t work :(

    any help in that area is highly appreciated :)

  11. I’ve been working with the Appcelerator team to figure this out –

    Apparently on iOS – the Titanium.Utils.Base64encode is not working properly in SDKs prior to the upcoming 1.8. There are javascript functions out there that will do the same thing.

    You can use one of those functions or download one of the latest nightly builds from Appcelerator to get a jump on mobile SDK 1.8.

    Hope this helps!

Post a comment.