【问题标题】:Hilt: provide BasicAuth to retrofit with user credentialsHilt:提供 BasicAuth 以使用用户凭据进行改造
【发布时间】:2021-11-17 20:36:13
【问题描述】:

我正在尝试使用 Hilt 重构我的第一个(编写不佳的)项目。 不幸的是,在我看过的所有教程中,没有人涵盖这个非常基本的案例:提供用户名和密码以改进基本身份验证。

我已经设置了网络模块,但是编译器正确地抱怨“provideRetrofitClient”函数的“无法注入字符串参数”。我想从视图模型传递的参数

视图模型:

@HiltViewModel
class AuthenticationViewModel
@Inject
constructor(
    private val apiService: ApiService
) : ViewModel() {

performLogin(username:String,password:String){
    viewModelScope.launch {
    //how can I pass credentials to apiService?
        apiService.login()
    }
}

网络模块:

Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

@Singleton
@Provides
fun provideGsonBuilder(): Gson = GsonBuilder().setLenient().create()


@Singleton
@Provides
fun provideRetrofitClient(username: String, password: String): OkHttpClient {
    return OkHttpClient.Builder()
        //this intercemptor allowed credentials set up in the original app
        //.addInterceptor(BasicAuthInterceptor(username, password))
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build()
}

@Singleton
@Provides
fun provideRetrofitBuilder(gsonBuilder: Gson, client: OkHttpClient): Retrofit.Builder {
    return Retrofit.Builder()
        .baseUrl(Constants.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gsonBuilder))
        .client(client)
}

@Singleton
@Provides
fun provideApiService(retrofitBuilder: Retrofit.Builder): ApiService {
    return retrofitBuilder
        .build()
        .create(ApiService::class.java)
}

如何在运行时使用凭据“配置”注入的改造客户端?

【问题讨论】:

    标签: android kotlin retrofit dagger-hilt


    【解决方案1】:

    NetworkModule 很可能不应该有provideRetrofitClient 函数的用户名/密码参数。这个函数应该只是创建服务并允许它被注入到你需要的地方。

    如果您的 API 需要用户名和密码作为请求的查询参数,则用户名和密码应通过 ApiService's login 函数作为 login(@Query("username") username: String, @Query("password") password: String) 提供。注意 - 查询注释中的字符串值取决于 API 期望的查询参数。

    如果您的 API 在正文或路径中需要用户名和密码,请查看 https://square.github.io/retrofit/ 以了解您的 login 函数应该如何使用的示例。

    然后,您可以通过 viewModel 函数 performLogin 传递用户名和密码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-04
      • 2016-08-03
      • 1970-01-01
      • 2012-06-26
      • 2010-10-07
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多