Android的OkHttp包处理用户认证的代码实例分享
更新时间:2016年07月13日 16:00:48 作者:成富
OkHttp包(GitHub主页github.com/square/okhttp)是一款高人气安卓HTTP支持包,这里我们来看一下Android的OkHttp包处理用户认证的代码实例分享:
OkHttp 提供了对用户认证的支持。当 HTTP 响应的状态代码是 401 时,OkHttp 会从设置的 Authenticator 对象中获取到新的 Request 对象并再次尝试发出请求。Authenticator 接口中的 authenticate 方法用来提供进行认证的 Request 对象,authenticateProxy 方法用来提供对代理服务器进行认证的 Request 对象。
用户认证的示例:
OkHttpClient client = new OkHttpClient();
client.setAuthenticator(new Authenticator() {
public Request authenticate(Proxy proxy, Response response) throws IOException {
String credential = Credentials.basic("user", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
public Request authenticateProxy(Proxy proxy, Response response)
throws IOException {
return null;
}
});
进阶
当需要实现一个 Basic challenge, 使用 Credentials.basic(username, password) 来编码请求头。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
client.setAuthenticator(new Authenticator() {
@Override public Request authenticate(Proxy proxy, Response response) {
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
@Override public Request authenticateProxy(Proxy proxy, Response response) {
return null; // Null indicates no attempt to authenticate.
}
});
Request request = new Request.Builder()
.url("http://publicobject.com/secrets/hellosecret.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
您可能感兴趣的文章:
- 详解Android中使用OkHttp发送HTTP的post请求的方法
- Android的OkHttp包中的HTTP拦截器Interceptor用法示例
- Android的HTTP扩展包OkHttp中的缓存功能使用方法解析
- Android M(6.x)使用OkHttp包解析和发送JSON请求的教程
- Android使用okHttp(get方式)下载图片
- 使用Android的OkHttp包实现基于HTTP协议的文件上传下载
- 详解Android使用OKHttp3实现下载(断点续传、显示进度)
- 使用OkHttp包在Android中进行HTTP头处理的教程
- Android使用okHttp(get方式)登录
- Android OkHttp的简单使用和封装详解
- Android-Okhttp的使用解析
相关文章
Android开发实现ImageView加载摄像头拍摄的大图功能
这篇文章主要介绍了Android开发实现ImageView加载摄像头拍摄的大图功能,涉及Android基于ImageView的摄像头拍摄图片加载、保存及权限控制等相关操作技巧,需要的朋友可以参考下2017-11-11


最新评论