你不应当使用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!