我在Stack 2上找到了基本授权方式。
第一是
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("login", "password");
return response.request().newBuilder().header("Authorization", credential).build();
}
和第二是
public class BasicAuthInterceptor implements Interceptor {
private String credentials;
public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}
我是初学者,所以我不知道应该实施哪些内容。 哪个更好?为什么 ?有人可以解释一下吗?