我正在使用 okhttp3 使用以下客户端构建器通过 SSL + 基本身份验证请求一些 Web 服务:
client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory())
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("myuser", "mypassword");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build()
然后我运行请求
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
Request request = requestBuilder.build();
Call call = client.newCall(request);
Response response = call.execute();
我得到一个 403(拒绝访问)。
我尝试使用 cURL 并且我得到了正确的身份验证。
我在函数中设置了一个断点,authenticate
似乎它甚至没有被调用。
如果我直接在中设置标题requestBuilder
,即
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
String credential = Credentials.basic("myuser", "mypassword");
requestBuilder.header("Authorization", credential).build();
Request request = requestBuilder.build();
Call call = client.newCall(request);
Response response = call.execute();
有用。
有什么建议吗?