且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Retrofit2身份验证错误到IBM的语音转文本

更新时间:2023-09-20 22:25:22

我为没有人能尽快解决这个问题感到难过,但这是我在从事其他项目时偶然遇到的解决方案

I am kind of saddened by the fact nobody was able to solve this one sooner, but here's the solution I came across by accident when working on a different project altogether.

curl命令可以看到,身份验证采用username: password模式的形式,在这种情况下,用户名是apikey字符串,密码是您的API密钥.

As you can see from the curl command, authentication comes in the form of username: password pattern, in this case, username being apikey string and password is your API key.

因此,您应该通过以下方式构建Retrofit实例来解决此问题:

So the way you should tackle this is by building your Retrofit instance this way:

fun init(token: String) {
    //Set logging interceptor to BODY and redact Authorization header
    interceptor.level = HttpLoggingInterceptor.Level.BODY
    interceptor.redactHeader("Authorization")

    //Build OkHttp client with logging and token interceptors
    val okhttp = OkHttpClient().newBuilder()
        .addInterceptor(interceptor)
        .addInterceptor(TokenInterceptor(token))
        .build()

    //Set field naming policy for Gson
    val gsonBuilder = GsonBuilder()
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)

    //Build Retrofit instance
    retrofit = Retrofit.Builder()
        .baseUrl(IBM_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
        .client(okhttp)
        .build()
}

并创建此自定义拦截器

class TokenInterceptor constructor(private val token: String) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        val requestBuilder = original
            .newBuilder()
            .addHeader("Authorization", Credentials.basic("apikey", token))
            .url(original.url)
        return chain.proceed(requestBuilder.build())
    }
}

您需要使用Credentials.basic()来对凭据进行编码.

You need to use Credentials.basic() in order to encode credentials.

我真的希望遇到类似问题的人偶然发现这一点并节省一些时间.

I really hope somebody with a similar issue stumbles across this and saves themselves some time.