android的http基础验证

你不应当使用http basic验证。那是不安全的,因为它通过请求头发送用户名和密码。你应当考虑一些像OAuth这样的来代替它。

但是撇开原由,有时候你会使用它。而且你会发现,没有具备证明文件的方法工作。你能在没有成功的情况下尝试他们的每个单独的方法。因此你不应道依赖Apache库的方法。你应道自己实现验证。


让我们切入正题:客户端这边验证包含一个被叫做Authorization的http头。它的值是一个Base64编码字符串,下面是它的格式:

username:password

编码之后,这个头将看起来像这样:

Authorization:Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

了解了这些,我们只是需要用那种格式创建一个header追加到请求中。

下面的代码要求Android 2.2才可以运行:

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()

对Base64.NOWRAP参数要特别注意,没有它,这个代码片段式不能运行的。

希望能有帮助。



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 themwithout 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值