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編程開發(fā)之TextView單擊鏈接彈出Activity的方法
這篇文章主要介紹了Android編程開發(fā)之TextView單擊鏈接彈出Activity的方法,涉及Android中TextView控件的相關操作技巧,需要的朋友可以參考下2016-01-01Android 如何獲取手機總內(nèi)存和可用內(nèi)存等信息
這篇文章主要介紹了Android系統(tǒng)檢測程序內(nèi)存占用各種方法,并對內(nèi)存信息的詳細介紹,需要的朋友可以參考下2016-07-07AsyncTask陷阱之:Handler,Looper與MessageQueue的詳解
本篇文章是對Handler,Looper與MessageQueue進行了詳細的分析介紹,需要的朋友參考下2013-05-05Android用RecyclerView實現(xiàn)動態(tài)添加本地圖片
本篇文章主要介紹了Android用RecyclerView實現(xiàn)動態(tài)添加本地圖片,具有一定的參考價值,有興趣的可以了解一下2017-08-08Android內(nèi)存泄漏檢測工具LeakCanary
在Android的性能優(yōu)化中,內(nèi)存優(yōu)化是必不可少的點,而內(nèi)存優(yōu)化最重要的一點就是解決內(nèi)存泄漏的問題,在Android的內(nèi)存泄漏分析工具也不少,比如PC端的有:AndroidStudio自帶的Android?Profiler、MAT等工具;手機端也有,就是我們今天要介紹的LeakCanary2023-04-04Android彈窗ListPopupWindow的簡單應用詳解
這篇文章主要為大家詳細介紹了Android彈窗ListPopupWindow的簡單應用,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11