Android的OkHttp包處理用戶認證的代碼實例分享
OkHttp 提供了對用戶認證的支持。當 HTTP 響應的狀態(tài)代碼是 401 時,OkHttp 會從設置的 Authenticator 對象中獲取到新的 Request 對象并再次嘗試發(fā)出請求。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;
}
});
進階
當需要實現(xiàn)一個 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發(fā)送HTTP的post請求的方法
- Android的OkHttp包中的HTTP攔截器Interceptor用法示例
- Android的HTTP擴展包OkHttp中的緩存功能使用方法解析
- Android M(6.x)使用OkHttp包解析和發(fā)送JSON請求的教程
- Android使用okHttp(get方式)下載圖片
- 使用Android的OkHttp包實現(xiàn)基于HTTP協(xié)議的文件上傳下載
- 詳解Android使用OKHttp3實現(xiàn)下載(斷點續(xù)傳、顯示進度)
- 使用OkHttp包在Android中進行HTTP頭處理的教程
- Android使用okHttp(get方式)登錄
- Android OkHttp的簡單使用和封裝詳解
- Android-Okhttp的使用解析
相關文章
完美解決Android三星手機從圖庫選擇照片旋轉(zhuǎn)問題
這篇文章主要幫助大家完美解決了Android三星手機從圖庫選擇照片旋轉(zhuǎn)問題,很實用的解決小案例,感興趣的小伙伴們可以參考一下2016-04-04
Android開發(fā)實現(xiàn)ImageView加載攝像頭拍攝的大圖功能
這篇文章主要介紹了Android開發(fā)實現(xiàn)ImageView加載攝像頭拍攝的大圖功能,涉及Android基于ImageView的攝像頭拍攝圖片加載、保存及權限控制等相關操作技巧,需要的朋友可以參考下2017-11-11
Android自定義控件eBook實現(xiàn)翻書效果實例詳解
這篇文章主要介紹了Android自定義控件eBook實現(xiàn)翻書效果的方法,結合實例形式分析了Android自定義控件實現(xiàn)翻書效果的具體步驟與相關操作技巧,需要的朋友可以參考下2016-10-10

