BASIC HTTP AUTHENTICATION ON ANDROID

BASIC HTTP AUTHENTICATION ON ANDROID

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 OAuthinstead.

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 calledAuthorization. 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!

Leocadio Tiné
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值