標籤: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!
android的http基礎驗證