【问题标题】:Get password protected json via Retrofit2 in Android通过 Android 中的 Retrofit2 获取受密码保护的 json
【发布时间】:2016-06-27 16:46:30
【问题描述】:

我成功使用了一个没有密码保护的 json,但管理员设置了密码,我无法通过 Retrofit2 获取数据。我怎样才能解决这个问题?请分享你的想法。谢谢。

【问题讨论】:

  • 管理员使用了什么身份验证方法(基本身份验证等)?
  • @CliveSeebregts 是的,它是一种基本的身份验证类型。

标签: android json web-services url retrofit2


【解决方案1】:

使用新的Authenticator 配置您的OkHttpClient 以处理Basic Auth,如下所示:

 OkHttpClient client = new OkHttpClient.Builder()
     .authenticator(new Authenticator() {
         @Override
         public Request authenticate(Route route, Response response) throws IOException {
             String credential = Credentials.basic("username", "password");
             return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
          }
      }).build();

然后在Retrofit中使用OkHttpClient如下:

new Retrofit.Builder()
            .baseUrl("url")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

【讨论】:

  • 你太棒了。感谢代码@Clive Seebregts
猜你喜欢
  • 2011-12-04
  • 1970-01-01
  • 2022-07-03
  • 2021-07-28
  • 1970-01-01
  • 2011-10-08
  • 1970-01-01
  • 2020-06-18
  • 2011-12-23
相关资源
最近更新 更多