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()); }
如对本文有疑问, 点击进行留言回复!!
Xamarin 安卓 相机 各种坑 目标API Android 6以后,我选的目标API版本是 Android 10
Android 9.0+软件某些功能突然暴毙:cleartext not permitted
Android : Resource is not a Drawable (color or path)
Flutter问题集锦——Android Studio 4.0.1 在AVD Manger中启动模拟器报“unable to locate abd”
网友评论