Traxdata 答案的修改版本有效:
protected Authenticator getBasicAuth(final String username, final String password) {
return new Authenticator() {
private int mCounter = 0;
@Override
public Request authenticate(Route route, Response response) throws IOException {
Log.d("OkHttp", "authenticate(Route route, Response response) | mCounter = " + mCounter);
if (mCounter++ > 0) {
Log.d("OkHttp", "authenticate(Route route, Response response) | I'll return null");
return null;
} else {
Log.d("OkHttp", "authenticate(Route route, Response response) | This is first time, I'll try to authenticate");
String credential = Credentials.basic(username, password);
return response.request().newBuilder().header("Authorization", credential).build();
}
}
};
}
然后你需要:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.authenticator(getBasicAuth("username", "pass"));
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
而已。