您的位置:首页 > 理论基础 > 计算机网络

Android学习记录(十二) http之base/digest鉴权。

2016-05-04 18:44 946 查看
说下背景,我们实现的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框架,欢迎推荐啊~

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android digest