1. 程式人生 > >Android學習記錄(十二) http之base/digest鑑權。

Android學習記錄(十二) http之base/digest鑑權。

說下背景,我們實現的http的檔案下載是基於webdav協議的。

這個肯定是需要鑑權的~

android 5.1不再推薦使用apache的client,今天努力想嘗試一下用httpurlconnection替換一下。

大家可以到stackoverflow搜尋一下,目前httpurlconnection還不支援digest鑑權,只支援base的鑑權。

下面是httpurlconnection base的鑑權程式碼:

HttpURLConnection conn=(HttpURLConnection)newurl.openConnection();
setJellyBeanAuth(conn);
private void setJellyBeanAuth(HttpURLConnection httpConn) {
    byte[] auth = (LoginManager
            .getCurrentUsername() + ":" + LoginManager
            .getCurrentPassword()).getBytes();
    String basic = Base64.encodeToString(auth, Base64.NO_WRAP);
    httpConn.setRequestProperty("Authorization"
, "Basic " + basic); }
然後偶們需要的是digest鑑權,所以還的老老實實使用httpclient
digest的鑑權程式碼如下:
HttpContext context = new BasicHttpContext();

context.setAttribute(ClientContext.CREDS_PROVIDER,
        new BasicCredentialsProvider());

CredentialsProvider provider = (CredentialsProvider) context
        .getAttribute(ClientContext.CREDS_PROVIDER
); provider.setCredentials( new AuthScope(targetHost.getHostName(), targetHost .getPort()), new UsernamePasswordCredentials(LoginManager .getCurrentUsername(), LoginManager .getCurrentPassword()));

關於httpurlconnection不支援digest的可以看這篇文章:
http://stackoverflow.com/questions/32689185/digest-authentication-in-android-using-httpurlconnection
如果有大牛看到這篇blog,有好的開源http框架,歡迎推薦啊~