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());}