Android的OkHttp包處理使用者認證的代碼執行個體分享_Android

來源:互聯網
上載者:User

OkHttp 提供了對使用者認證的支援。當 HTTP 響應的狀態碼是 401 時,OkHttp 會從設定的 Authenticator 對象中擷取到新的 Request 對象並再次嘗試發出請求。Authenticator 介面中的 authenticate 方法用來提供進行認證的 Request 對象,authenticateProxy 方法用來提供對Proxy 伺服器進行認證的 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());}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.