手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >Android的OkHttp包处理用户认证的代码实例分享
Android的OkHttp包处理用户认证的代码实例分享
摘要:OkHttp提供了对用户认证的支持。当HTTP响应的状态代码是401时,OkHttp会从设置的Authenticator对象中获取到新的Re...

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包处理用户认证的代码实例分享】相关文章:

Android中利用App实现消息推送机制的代码

Android基站定位原理及实现代码

Android编程设置全屏的方法实例

Android的Touch事件处理机制介绍

android IntentService实现原理及内部代码分享

Android三种菜单实例分析

Android 图片特效处理的方法实例

Adapter实现ListView带多选框等状态的自定义控件的注意事项

Android 情景模式的设置代码

Android通过手势实现的缩放处理实例代码

精品推荐
分类导航