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

来源:互联网 发布:企业沟通软件 编辑:程序博客网 时间:2024/06/05 16:39

说下背景,我们实现的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框架,欢迎推荐啊~

0 0
原创粉丝点击