在 OkHttp3 中,您OkHttpClient
通过添加authenticator()
方法来设置自身的授权。在您的原始呼叫返回 401 响应后,the authenticator()
添加Authorization
标题
new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.readTimeout(10000, TimeUnit.MILLISECONDS)
.authenticator(new Authenticator() {
@Nullable
@Override
public Request authenticate(@NonNull Route route, @NonNull Response response) {
if (response.request().header(HttpHeaders.AUTHORIZATION) != null)
return null; //if you've tried to authorize and failed, give up
String credential = Credentials.basic("username", "pass");
return response.request().newBuilder().header(HttpHeaders.AUTHORIZATION, credential).build();
}
})
.build();
虽然它更安全,但如果您不想一开始就向服务器发送所有 401 请求的垃圾邮件,您可以使用称为 preauthentication 的东西,在其中发送Authorization
标头以开始您的请求
String credentials = Credentials.basic("username", "password");
Request httpRequest = new Request.Builder()
.url("some/url")
.header("content-type", "application/json")
.header(HttpHeaders.AUTHORIZATION, credentials)
.build();