Android的OkHttp使用基本身份验证身份验证、基本、Android、OkHttp

2023-09-06 02:08:21 作者:迷失在那温暖笑脸中゜

我使用OkHttp库一个新项目,就是IM pressed其易用性。我现在有一个需要使用基本身份验证。不幸的是,工作样本code缺乏。我正在寻求如何通过用户名/密码凭据OkAuthenticator一个HTTP 401头时遇到的一个例子。我认为这样的回答:

I'm using the OkHttp library for a new project and am impressed with its ease of use. I now have a need to use Basic Authentication. Unfortunately, there is a dearth of working sample code. I'm seeking an example of how to pass username / password credentials to the OkAuthenticator when an HTTP 401 header is encountered. I viewed this answer:

Retrofit POST请求瓦特/基本HTTP认证:"不能重试流HTTP身体QUOT;

但它没有让我太远。在 OkHttp GitHub库没有特色的认证为基础的样品或者样品。有没有人有让我指出了正确的方向上的要点或其他code样?感谢您的帮助!

but it didn't get me too far. The samples on the OkHttp github repo didn't feature an authentication-based sample either. Does anyone have a gist or other code sample to get me pointed in the right direction? Thanks for your assistance!

推荐答案

尝试使用OkAuthenticator:

client.setAuthenticator(new OkAuthenticator() {
  @Override public Credential authenticate(
      Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
    return Credential.basic("scott", "tiger");
  }

  @Override public Credential authenticateProxy(
      Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
    return null;
  }
});