Android的OkHttp包处理用户认证的代码实例分享
OkHttp提供了对用户认证的支持。当HTTP响应的状态代码是401时,OkHttp会从设置的Authenticator对象中获取到新的Request对象并再次尝试发出请求。Authenticator接口中的authenticate方法用来提供进行认证的Request对象,authenticateProxy方法用来提供对代理服务器进行认证的Request对象。
用户认证的示例:
OkHttpClientclient=newOkHttpClient(); client.setAuthenticator(newAuthenticator(){ publicRequestauthenticate(Proxyproxy,Responseresponse)throwsIOException{ Stringcredential=Credentials.basic("user","password"); returnresponse.request().newBuilder() .header("Authorization",credential) .build(); } publicRequestauthenticateProxy(Proxyproxy,Responseresponse) throwsIOException{ returnnull; } });
进阶
当需要实现一个Basicchallenge,使用Credentials.basic(username,password)来编码请求头。
privatefinalOkHttpClientclient=newOkHttpClient(); publicvoidrun()throwsException{ client.setAuthenticator(newAuthenticator(){ @OverridepublicRequestauthenticate(Proxyproxy,Responseresponse){ System.out.println("Authenticatingforresponse:"+response); System.out.println("Challenges:"+response.challenges()); Stringcredential=Credentials.basic("jesse","password1"); returnresponse.request().newBuilder() .header("Authorization",credential) .build(); } @OverridepublicRequestauthenticateProxy(Proxyproxy,Responseresponse){ returnnull;//Nullindicatesnoattempttoauthenticate. } }); Requestrequest=newRequest.Builder() .url("http://publicobject.com/secrets/hellosecret.txt") .build(); Responseresponse=client.newCall(request).execute(); if(!response.isSuccessful())thrownewIOException("Unexpectedcode"+response); System.out.println(response.body().string()); }