这里有新鲜出炉的精品教程,程序狗速度看过来!
Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。
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());
- }
来源: http://www.phperz.com/article/17/0917/348553.html