簡體   English   中英

IBM 的 Speech to Text 的 Retrofit2 身份驗證錯誤

[英]Retrofit2 authentication error to IBM's Speech to Text

我試圖在不使用庫的情況下訪問 IBM 的 Speech to Text 服務。 我正在使用 Retrofit 和 GSON。

問題出在身份驗證中,顯然沒有正確發生,返回代碼 401。從官方文檔中,HTTP 請求應該采用這種格式

curl -X POST -u "apikey:{apikey}" \
--header "Content-Type: audio/flac" \
--data-binary @{path_to_file}audio-file.flac \
"{url}/v1/recognize"

當我使用我的憑據測試curl命令時,該服務運行良好。

這是我正在使用的界面

interface SpeechToTextApi {

    @Multipart
    @POST("v1/recognize")
    fun speechToText(
        @Header("Authorization") authKey: String,
        @Part("file") filename: RequestBody,
        @Part voiceFile: MultipartBody.Part
    ): Call<List<SpeechToText>>
}

我有以下數據類

data class SpeechToText(val results: List<SttResult>)
data class SttResult(val alternatives: List<RecognitionResult>, val final: Boolean)
data class RecognitionResult(val confidence: Float, val transcript: String)

這就是我設置 Retrofit 的方式

private val retrofit = Retrofit.Builder()
        .baseUrl(STT_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

private val service = retrofit.create(SpeechToTextApi::class.java)

調用實際服務時看起來像這樣

val requestFile = RequestBody.create(MediaType.parse("audio/mp3"), file.name)
val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
service
    .speechToText(getString(R.string.stt_iam_api_key), requestFile, body)
    .enqueue(object: Callback<List<SpeechToText>> {
    override fun onResponse(call: Call<List<SpeechToText>>, response: Response<List<SpeechToText>>) {
        val listOfStts = response.body()
        Log.d(TAG, "Response code: ${response.code()}")
        if (listOfStts != null) {
            for (stt in listOfStts) {
                for (res in stt.results) {
                    Log.d(TAG, "Final value: ${res.final}")
                    for (alt in res.alternatives) {
                        Log.d(TAG, "Alternative confidence: ${alt.confidence}\nTranscript: ${alt.transcript}")
                        Toast.makeText(this@MainActivity, alt.transcript, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    override fun onFailure(call: Call<List<SpeechToText>>, t: Throwable) {
        Log.d(TAG, "Error: ${t.message}")
        t.printStackTrace()
    }
})

錄音是 MP3 文件,我確信它們存儲正確且可訪問。 我也用audio/mp3替換了audio/flac

問題似乎在於身份驗證的工作方式。 在我上面顯示的代碼之前,我使用過

private val retrofit = Retrofit.Builder()
        .baseUrl(STT_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(OkHttpClient.Builder()
            .addInterceptor { chain ->
                val request = chain.request()
                val headers = request
                    .headers()
                    .newBuilder()
                    .add("Authorization", getString(R.string.stt_iam_api_key))
                    .build()
                val finalRequest = request.newBuilder().headers(headers).build()
                chain.proceed(finalRequest)
            }
            .build())
    .build()

但相同的響應代碼 401 仍然存在。 當然,接口方法缺少@Header參數。

非常感謝任何形式的幫助。

我對沒有人能夠更早解決這個問題感到有點難過,但這是我在完全不同的項目上工作時偶然遇到的解決方案。

curl命令可以看出,身份驗證采用username: password模式的形式,在這種情況下,用戶名是apikey字符串,密碼是您的 API 密鑰。

所以你應該解決這個問題的方法是這樣構建你的 Retrofit 實例:

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()來對憑證進行編碼。

我真的希望有類似問題的人偶然發現這一點並節省一些時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM