BASIC HTTP AUTHENTICATION ON ANDROID

来源:互联网 发布:ios sql 编辑:程序博客网 时间:2024/05/21 23:33

This post belongs to the Day-saver snippets category, which is a series of simple code samples that will save you a day of research, which was exactly what they cost me.

You shouldn’t use HTTP basic authentication. It’s unsafe, since it sends the username and the password through the request headers. You should consider something like OAuth instead.

But, reasons aside, sometimes you’ll need to use it. And you’ll find that none of the documented methods work. You can try every single one of them without success. So you shouldn’t rely on the methods of the Apache library. You should do the authentication yourself.

HOW IT WORKS

Let’s cut to the chase: the client-side authentication consists on a HTTP header called Authorization. Its value is a Base64-encoded string, with the following format:

username:password
After encoded, the header will look like this:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Knowing that, we just need to create a header with that format and append to the request.

THE SNIPPET

Tho code below requires Android 2.2 to work (API level 8):

HttpUriRequest request = new HttpGet(YOUR_URL); // Or HttpPost(), depends on your needs
String credentials = YOUR_USERNAME + “:” + YOUR_PASSWORD;
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader(“Authorization”, “Basic ” + base64EncodedCredentials);

HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(request);
// You’ll need to handle the exceptions thrown by execute()
Pay special attention to the Base64.NO_WRAP param. Without it, the snippet won’t work.

Hope it helps!

0 0
原创粉丝点击